374. Guess Number Higher or Lower
Posted andywu
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 (-1
, 1
, 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 }
以上是关于374. Guess Number Higher or Lower的主要内容,如果未能解决你的问题,请参考以下文章
374. Guess Number Higher or Lower
374. Guess Number Higher or Lower
374. Guess Number Higher or Lower
374. Guess Number Higher or Lower