374. Guess Number Higher or Lower

来源:互联网 发布:日本尺八制作数据 编辑:程序博客网 时间:2024/06/05 11:59

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.


猜数字。用二分法。


代码:

int guess(int num){if(num == pick) return 0;return pick < num ? -1 : 1;}class Solution{public:int guessNumber(int n){int l = 1, r = n;while(true){int mid = (r - l) / 2 + l, val = guess(mid);if(val < 0){r = mid - 1;}else if(val > 0){l = mid + 1;}else{return mid;}}}};


0 0
原创粉丝点击