Leetcode Guess Number Higher or Lower problem solution

In this Leetcode Guess Number Higher or Lower problem solution, 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 3 possible results:

  1. -1: The number I picked is lower than your guess (i.e. pick < num).
  2. 1: The number I picked is higher than your guess (i.e. pick > num).
  3. 0: The number I picked is equal to your guess (i.e. pick == num).

Return the number that I picked.

Leetcode Guess Number Higher or Lower problem solution


Problem solution in Python.

class Solution(object):
    def guessNumber(self, n):
        """
        :type n: int
        :rtype: int
        """
        left,right = 1,n
        while left<=right:
            mid = (left+right)/2
            gues = guess(mid)
            if gues == 0:
                return mid
            if gues == -1:
                right = mid -1
            if gues == 1:
                left = mid+1
        return -1



Problem solution in Java.

public class Solution extends GuessGame {
    public int guessNumber(int n) {
        int left = 1;
        int right = n;
        while(left < right){
            int myPick = left + (right - left )/ 2;
            if(guess(myPick) == 0) return myPick;
            else if(guess(myPick) == 1){
                left = myPick + 1;
            }
            else{
                right = myPick - 1;
            }
        }
        return left;
    }
}


Problem solution in C++.

int guess(int num);

class Solution {
public:
    int guessNumber(int n) {
        if (guess(n) == 0)
            return n;
        int i = 1;
        int j = n;
        while (i < j) {
            int mid = i + (j - i) / 2;
            int tmp = guess(mid);
            if (tmp == 0)
                return mid;
            else if (tmp == 1)
                i = mid + 1;
            else
                j = mid - 1;
        }
        return i;
    }
};


Problem solution in C.

int guessNumber(int n){
    int l = 1, h = n;
    
    while(l <= h){
        int mid = l + (h-l)/2;
        
        if(guess(mid) == 0) return mid;
        else if(guess(mid) == 1){
            l = mid+1;
            mid = l + (h-l)/2;
        }
        else{
            h = mid-1;
            mid = l + (h-l)/2;
        }
    }
    return -1;
}


Post a Comment

0 Comments