My c++ solution is wrong. But why???


  • 0
    Y

    // 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 low,high,mid;
            low=1;high=n;
            while(low<=high)
            {
                mid=low+(high-low)/2;
                if(guess(mid)==0) 
                return mid;
                else if(guess(mid)==1) 
                high=mid-1;
                else
                low=mid+1;
            }
            return 0;
        }
    };
    

  • 1
    G

    Actually I think the description of guess API is wrong.
    Correction: guess API will return 1 if your input number is lower, -1 if your input number is higher!
    Therefore, your code gonna be:

    else if(guess(mid)==-1)
    high=mid-1;
    else
    low=mid+1;
    }
    ```

  • 0

    @yuluodi @Garlicala Both of you guys just cannot format your code using ``` backquotes please. I helped you guys out this time, be more careful next time, Okay?

    @Garlicala's idea is right though

    The description here is a way to make it more tricky, so don't complain here.


  • 0
    M
    This post is deleted!

  • 0
    M

    @LHearen

    //this is not a complanation
    /*
    They are asking questions which I think is exactly what they should do in this forum. However I think you are the one complaining, and seems you hate them asking questions. You are really RUDE and OFFENSIVE.";
    */
    

Log in to reply
 

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