# Guess Number Higher or Lower

{% embed url="<https://www.lintcode.com/problem/662/>" %}

## Solution 1 (Java)

```java
/* The guess API is defined in the parent class GuessGame.
   @param num, your guess
   @return -1 if my number is lower, 1 if my number is higher, otherwise return 0
      int guess(int num); */

public class Solution extends GuessGame {
    /**
     * @param n an integer
     * @return the number you guess
     */
    public int guessNumber(int n) {
        final int CORRECT = 0, GUESS_SMALLER = -1, GUESS_LARGER = 1;
        int left = 1, right = n;
        while (left + 1 < right) {
            int mid = left + (right - left) / 2;
            if (guess(mid) == CORRECT) {
                return mid;
            } else if (guess(mid) == GUESS_SMALLER) {
                right = mid;
            } else { // (guess(mid) == GUESS_LARGER)
                left = mid;
            }
        }

        if (guess(left) == CORRECT) return left;
        if (guess(right) == CORRECT) return right;
        return 0;
    }
}
```

### Notes

* This is almost the same as [classical binary search](/algo/binary-search/classical-binary-search.md).


---

# 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://blog.yushunchen.com/algo/binary-search/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.
