[LeetCode] 374. 猜数字大小

考察二分的一种写法,注意数据的溢出

public class Solution extends GuessGame {
    public int guessNumber(int n) {
        int left = 1;
        int right = n;
        while (left <= right) {
            int mid = left + ((right - left) >> 1);
            int ret = guess(mid);
            if (ret == 0) return mid;
            if (ret == -1) {
                right = mid - 1;
            } else {
                left = mid + 1;
            }
        }

        return -1;
    }
}
原文地址:https://www.cnblogs.com/acbingo/p/14883838.html