本题没有难度,就用二分法查找就好了,但是有一个需要注意的地方
int mid=(end-front)/2+front;//防止溢出的写法
一开始我是写成mid=(front+end)/2;front+end的值太大会溢出
可以用位运算>>1右移一位相当于除以2
当然也可以用代码中先减后加的方法。
今天在CSDN上看了一个求两个数的平均值的算法:Avg = (ValueA & ValueB) +
(ValueA ^ ValueB) >>1,
这种方法避免了应用Avg=(ValueA+ValueB)/2时,ValueA+ValueB造成的溢出。
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);
class Solution {
public:
int guessNumber(int n) {
int front=1;
int end=n;
while(1)
{int mid=(end-front)/2+front;//防止溢出的写法
int re;
re=guess(mid);
if(re>0)
front=mid+1;
else if(re<0)
end=mid-1;
else
return mid;
}
}
};