Guess

solution:

// Forward declaration of guess API.
// @param num, your guess
// @return -1 if my number is lower, 1 if my number is higher, otherwise return 0
int guess(int num);

class Solution {
public:
    //注意的是guess函数到底是谁的数字。
    int guessNumber(int n) {
        //if(guess(n)==0) return n;//err.
        int left = 1, right = n, mid;
        while(left<=right)
        {
            mid = left + (right-left)*0.5;
            int t = guess(mid);
            if(t==1) left = mid+1;
            else if(t== -1) right = mid-1;
            else return mid;
        }
        return left;
    }
};

猜你喜欢

转载自www.cnblogs.com/happyamyhope/p/10461349.html