猜數字大小(簡單)
2020年6月23日
題目來源:力扣
解題
看題目就是一道普通的二分題了。
這裏取中間數,我一開始用(l+r)/2超時了,想想應該是數據量過大可能導致整型溢出,後面改成了l+(r-l)/2。
/**
* Forward declaration of guess API.
* @param num your guess
* @return -1 if num is lower than the guess number
* 1 if num is higher than the guess number
* otherwise return 0
* int guess(int num);
*/
public class Solution extends GuessGame {
public int guessNumber(int n) {
int l=1;
int r=n;
while(l<=r){
int c=l+(r-l)/2;
int num=guess(c);
if(num==0) return c;
else if(num==-1) r=c-1;
else l=c+1;
}
return -1;
}
}