LeetCode—猜数字大小(二分)

猜数字大小(简单)

2020年6月23日

题目来源:力扣

在这里插入图片描述

解题

看题目就是一道普通的二分题了。

这里取中间数,我一开始用(l+r)/2超时了,想想应该是数据量过大可能导致整型溢出,后面改成了l+(r-l)/2。

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

public class Solution extends GuessGame {
    public int guessNumber(int n) {
        int l=1;
        int r=n;
        while(l<=r){
            int c=l+(r-l)/2;
            int num=guess(c);
            if(num==0) return c;
            else if(num==-1) r=c-1;
            else l=c+1;
        }
        return -1;
    }
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_41541562/article/details/106916781