LeetCode374. Guess Number Higher or Lower——二分查找

文章目录

一、题目

We are playing the Guess Game. The game is as follows:

I pick a number from 1 to n. You have to guess which number I picked.

Every time you guess wrong, I will tell you whether the number I picked is higher or lower than your guess.

You call a pre-defined API int guess(int num), which returns three possible results:

-1: Your guess is higher than the number I picked (i.e. num > pick).

1: Your guess is lower than the number I picked (i.e. num < pick).

0: your guess is equal to the number I picked (i.e. num == pick).

Return the number that I picked.

Example 1:

Input: n = 10, pick = 6

Output: 6

Example 2:

Input: n = 1, pick = 1

Output: 1

Example 3:

Input: n = 2, pick = 1

Output: 1

Constraints:

1 <= n <= 231 - 1

1 <= pick <= n

二、题解

cpp 复制代码
/** 
 * Forward declaration of guess API.
 * @param  num   your guess
 * @return 	     -1 if num is higher than the picked number
 *			      1 if num is lower than the picked 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 = l + ((r - l) >> 1);
            if(guess(mid) == 0) return mid;
            else if(guess(mid) == 1) l = mid + 1;
            else r = mid - 1;
        }
        return 0;
    }
};
相关推荐
_院长大人_27 分钟前
设计模式-工厂模式
java·开发语言·设计模式
MATLAB代码顾问29 分钟前
MATLAB实现决策树数值预测
开发语言·决策树·matlab
priority_key1 小时前
排序算法:堆排序、快速排序、归并排序
java·后端·算法·排序算法·归并排序·堆排序·快速排序
不染尘.2 小时前
2025_11_7_刷题
开发语言·c++·vscode·算法
似水এ᭄往昔2 小时前
【C++】--stack和queue
开发语言·c++
csbysj20202 小时前
R 绘图 - 散点图
开发语言
会跑的兔子3 小时前
Android 16 Kotlin协程 第一部分
android·开发语言·kotlin
来荔枝一大筐3 小时前
力扣 寻找两个正序数组的中位数
算法
Js_cold3 小时前
Verilog函数function
开发语言·fpga开发·verilog
我是苏苏3 小时前
C#基础:如何从现有类库复制一个新的类库,并且加入解决方案
开发语言·c#