Guess Number Higher or Lower

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.

LeetCode Problem - 374 : Link | Click Here

public class Solution extends GuessGame {
    // Function to guess the correct number using binary search
    public int guessNumber(int n) {
        // If the guess for the maximum value is correct, return it
        if (guess(n) == 0) return n;

        // If the guess for the minimum value is correct, return it
        if (guess(1) == 0) return 1;

        // Initialize variables to keep track of the correct number, first number, and end number
        int correctNum = 0;
        int firstNum = 1;
        int endNum = n;

        // Perform binary search
        while (firstNum < endNum) {
            // Calculate mid point
            int mid = firstNum + (endNum - firstNum) / 2;

            // Check the guess result for the mid point
            if (guess(mid) == -1) {
                // If the guess is too high, update the end number to mid
                endNum = mid;
            } else if (guess(mid) == 1) {
                // If the guess is too low, update the first number to mid + 1
                firstNum = mid + 1;
            } else {
                // If the guess is correct, update the correctNum and break out of the loop
                correctNum = mid;
                break;
            }
        }

        // Return the correct number
        return correctNum;
    }
}

Did you find this article valuable?

Support Perf Insights by becoming a sponsor. Any amount is appreciated!