374. Guess Number Higher or Lower

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):

-1 : My number is lower
 1 : My number is higher
 0 : Congrats! You got it!

Example:

n = 10, I pick 6.

Return 6.
题目含义:1到n里面选了一个数,让你来猜是哪一个。
如果目标数比你猜的数小,返回-1,
如果目标数比你猜的数大,返回1,
如果两数相等,返回0

 1     public int guessNumber(int n) {
 2         if (guess(n) == 0) return n;
 3         int left = 1,right =n;
 4         while (left<right)
 5         {
 6             int mid = left + (right - left) / 2;
 7             int t = guess(mid);
 8             if (t == 0 )return mid;
 9             else if (t>0) left=mid;
10             else right = mid;
11         }
12         return left;        
13     }

 



posted @ 2017-10-24 15:10  daniel456  阅读(116)  评论(0编辑  收藏  举报