🌗 374. 猜数字大小
2022年10月10日
- algorithm
🌗 374. 猜数字大小
难度: 🌗
问题描述
解法
/**
* 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) {
// 思路:
// 根据题意写出表达式
return mySol(1, n);
}
private int mySol(int low, int high) {
// 递归终止条件
if(low == high) {
return low;
}
// 二分,首先判断与中点的大小
int mid = low + (int)(((long)high - low) >> 1);
int tmp = guess(mid);
if(tmp == 0) {
return mid;
} else if(tmp < 0) {
return mySol(low, mid - 1);
} else {
return mySol(mid + 1, high);
}
}
}