leetcode 374猜数字大小

 

// 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:
    int guessNumber(int n) {
        int left=1,right=n;
        while(left<=right){
            int mid=left+(right-left)/2;  
            int g=guess(mid);
            if(g==0)
                return mid;
            if(g<0)
                right=mid-1;
            else
                left=mid+1;
        }
        return 0;
    }
};

 

posted @ 2019-04-13 23:14  Joel_Wang  阅读(160)  评论(0编辑  收藏  举报