https://leetcode.com/problems/guess-number-higher-or-lower/description/
Solution 1. Recursion.
int guessing(int lo, int hi) {
int mi = (hi - lo)/2 + lo;
int c = guess(mi);
if(c==0) return mi;
else if(c==1) return guessing(mi+1, hi);
else return guessing(lo, mi-1);
}
int guessNumber(int n) {
return guessing(1, n);
}
Solution 2. Iteration.
int guessNumber(int n) {
int mi, re, hi = n, lo = 1;
while(true) {
mi = (hi - lo)/2 + lo;
re = guess(mi);
if(re == 0) return mi;
else if(re == 1) lo = mi + 1;
else hi = mi - 1;
}
}
No comments:
Post a Comment