C++ solution by updating lower and upper boundary


  • 0
    M
    // 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 max_num = n;
            int min_num = 1;
            int mid_num;
            while(true){
                mid_num = (max_num - min_num) / 2 + min_num;
                int res = guess(mid_num);
                if(res == 0){
                    return mid_num;
                }
                else if(res == -1){
                    max_num = mid_num - 1;
                }else{
                    min_num = mid_num + 1;
                }
            }
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.