# 374.Guess Number Higher or Lower

**374.Guess Number Higher or Lower**

难度:Easy

> 我们正在玩一个猜数字游戏。 游戏规则如下： 我从 1 到 n 选择一个数字。 你需要猜我选择了哪个数字。 每次你猜错了，我会告诉你这个数字是大了还是小了。 你调用一个预先定义好的接口 guess(int num)，它会返回 3 个可能的结果（-1，1 或 0）： -1 : 我的数字比较小 1 : 我的数字比较大 0 : 恭喜！你猜对了！

```
示例 :

输入: n = 10, pick = 6
输出: 6
```

方法：二分法。 需要注意一些特殊情况。当mid==start时，有可能无限循环。比如(1+2)/2=1,这时将mid++即可。代码如下:

```
// 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 start=1;
        int ed=n;
        int t=1;
        int mid;
        while(start<ed)
        {
            mid=start+(ed-start)/2;
            
          //  cout <<start<<" "<<ed<<" "<< mid<<" "<<t<<endl;
            t=guess(mid);
            if(t==0) return mid;
            if(mid==start) mid++;
            if(t==-1)
                ed=mid;              
            else if(t== 1)
                start=mid;
          
           
        }
       // cout<<guess(7)<<endl;
        return start;
    }
};
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://dfine.gitbook.io/leetcode/374.guess_number_higher_or_lower.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
