力扣-374题 猜数字大小(C++)- 二分

题目链接:https://leetcode-cn.com/problems/guess-number-higher-or-lower/
题目如下:
在这里插入图片描述
在这里插入图片描述

/** 
 * 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);
 */

class Solution {
    
    
public:
    int guessNumber(int n) {
    
    
        int l=1,r=n;
        while(l<r){
    
    
            int mid=(long long)l+r>>1;
            if(guess(mid)<=0){
    
    //mid大了
                r=mid;
            }else{
    
    //mid小了
                l=mid+1;
            }
        }

        return r;
    }
};

おすすめ

転載: blog.csdn.net/qq_40467670/article/details/121296993