题目:
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 will tell you whether the number I picked is higher or lower than your guess.
You call a pre-defined API int guess(int num), which returns three possible results:
-1: Your guess is higher than the number I picked (i.e. num > pick).
1: Your guess is lower than the number I picked (i.e. num < pick).
0: your guess is equal to the number I picked (i.e. num == pick).
Return the number that I picked.
// !给了你 int guess(int num) 函数,直接用~
非常简单的二分查找法
// 记住,题目给了你int guess(int num)的函数了
var guessNumber = function(n) {
let left=1
let right=n;
while(left<=right){ //易错一:<=
mid=Math.floor(left+(right-left)/2); //易错二:!!math.floor 不要忘记!!
if(guess(mid)===0){
return mid;
}
else if(guess(mid)===-1){
right=mid-1;
}
else{
left=mid+1;
}
}
return -1;
};