374. Guess Number Higher or Lower

时间:2023-03-09 18:44:28
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.

我从1到n之间选择一个数字,由你来猜我选了哪个数字。

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

你可以用一个已经准备好的接口guess(int num),它会返回3个可能的结果(-1,1或0):

-1 : My number is lower    //我的数字更小
1 : My number is higher   //我的数字更大
0 : Congrats! You got it!  //猜中了

刚开始第一次提交采用了二分查找,不过显示超时了。

超时case: 2126753390

       1702766719

看讨论发现是溢出了,所以改了下程序。

 // Forward declaration of guess API.
// @param num, your guess
// @return -1 if my number is lower, 1 if my number is higher, otherwise return 0
int guess(int num); class Solution {
public:
int guessNumber(int n) {
int low=,high=n,g,r;
while(low<=high){
g=(low+high)/;  //改成g=low+(high-low)/2;
r=guess(g);
if(r==-)high=g-;
else if(r==)low=g+;
else return g;
}
return ;
}
};