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.
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.
就是一個二分法找數的題
public int guessNumber(int n) {
int low = 1;
int high = n;
int mid = low + (high - low) / 2;
while (low < high) {
if(guess(mid) == 0) return mid;
else if(guess(mid) == -1)high = mid;
else if(guess(mid) == 1)low = mid+1;
}
return low;
}
計算mid的時候一定要寫成 mid = low +(high - low) / 2;
而不要寫成mid = (low + high)/2
因為第二種有可能會造成溢位,謹記
相關文章
- Straightforward Lower BoundAIForward
- Higher-order Graph Neural Networks
- 高階函式 - Higher Order Function函式Function
- lower_case_table_names
- C++ lower_bound upper_boundC++
- gem5 CPU ISA level is lower than requiredUI
- JavaScript Number()JavaScript
- ORA-65294: PDB's compatible parameter value (12.2.0.1.0) is higher than CDB's
- JavaScript Number 物件JavaScript物件
- Leetcode Number of islandsLeetCode
- Kata:Hamming number
- JavaScript Number toLocaleString()JavaScript
- JavaScript Number toString()JavaScript
- Number.NaNNaN
- MySQL8.0的坑之lower_case_table_namesMySql
- Serial number lookup for Panasonic
- D. The Number of Imposters
- Big Number hd 1212
- 7.104 ITERATION_NUMBER
- Leetcode 447 Number of BoomerangsLeetCodeOOM
- react input[type='number']React
- number(p,s)(轉)
- Last digit of a huge numberASTGit
- [HNU 10072] Fibonacci Number
- Python Number(數字)Python
- Perfect Number 完美數
- [LeetCode] Third Maximum NumberLeetCode
- [LeetCode] Find the Duplicate NumberLeetCode
- Leetcode 9 Palindrome NumberLeetCode
- 136. Single Number
- Number.parseInt() 方法
- Number.parseFloat()方法
- Number.isSafeInteger()方法
- Number.isNaN()方法NaN
- Number.isFinite()方法
- Js中的NumberJS
- Number.POSITIVE_INFINITY
- Number.ATIVE_INFINITY