Steward
分享是一種喜悅、更是一種幸福
程式語言 - LeetCode - C++ - 374. Guess Number Higher or Lower
參考資訊:
https://algo.monster/liteproblems/374
https://www.cnblogs.com/grandyang/p/5666502.html
題目:

解答:
/**
* Forward declaration of guess API.
* @param num your guess
* @return -1 if num is higher than the picked number
* 1 if num is lower than the picked number
* otherwise return 0
* int guess(int num);
*/
class Solution {
public:
int guessNumber(int n) {
long left = 0;
long right = n;
while (left < right) {
int v = left + ((right - left) / 2);
int r = guess(v);
if (r < 0) {
right = v;
}
else if (r > 0) {
left = v + 1;
}
else {
return v;
}
}
return left;
}
};