Skip to content

Latest commit

 

History

History
91 lines (70 loc) · 2.13 KB

_374. Guess Number Higher or Lower.md

File metadata and controls

91 lines (70 loc) · 2.13 KB

All prompts are owned by LeetCode. To view the prompt, click the title link above.

Back to top


First completed : June 02, 2024

Last updated : July 01, 2024


Related Topics : Binary Search, Interactive

Acceptance Rate : 55.26 %


Solutions

Java

// This is just bin search but with casting to long cause of int overflow lol

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

 public class Solution extends GuessGame {
    public int guessNumber(int n) {
        int left = 1, right = n;

        while (left < right) {
            int mid = (int) (((long) left + (long) right) / 2);
            int gs = guess(mid);

            if (gs == 0) {
                return mid;
            }

            if (gs == -1) {
                right = mid - 1;
            } else {
                left = mid + 1;
            }
        }
        return left;
        
    }
}

Python

# The guess API is already defined for you.
# @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
# def guess(num: int) -> int:

class Solution:
    def guessNumber(self, n: int) -> int:
        left, right = 1, n
        
        while left < right :
            mid = (left + right) // 2
            gs = guess(mid)

            match gs :
                case -1 :
                    right = mid - 1
                case 1 :
                    left = mid + 1
                case 0 :
                    return mid
        
        return left