google code prettify

2016年7月16日 星期六

LeetCode - 374. Guess Number Higher or Lower

Question:

We are playing the Guess Game. The game is as follows:
I pick a number from 1 to n. You have to guess which number I picked.
Every time you guess wrong, I'll tell you whether the number is higher or lower.
You call a pre-defined API guess(int num) which returns 3 possible results (-11, or 0):

Solution:


public class Solution extends GuessGame {
    
    public int guessNumber(int n) {
        Long R = new Long(n);
  Long L = 1L;
   
  if(R!=L){
   while(R>=L){
    Long mid = ((L+R)>>1);

    int result = guess(mid.intValue());
    //System.out.println("mid:" + mid + " ,result:" + result);
    if(result ==1){
     L = mid+1;
     
    }else if(result ==-1){
     R = mid-1;
    }else{
        return mid.intValue();
    }
   }
  }else{
      return R.intValue();
  }
  
  
  return L.intValue();
  
 }
}

沒有留言:

張貼留言