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

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

 1 // Forward declaration of guess API.
 2 // @param num, your guess
 3 // @return -1 if my number is lower, 1 if my number is higher, otherwise return 0
 4 int guess(int num);
 5 
 6 class Solution {
 7 public:
 8     int guessNumber(int n) {
 9         int low=1,high=n,g,r;
10         while(low<=high){
11             g=(low+high)/2;  //改成g=low+(high-low)/2;
12             r=guess(g);
13             if(r==-1)high=g-1;
14             else if(r==1)low=g+1;
15             else return g;
16         }
17         return 0;
18     }
19 };

原文地址:https://www.cnblogs.com/Z-Sky/p/5678666.html