Cannot pass testcase"2147395599"


  • 0
    K
    int mySqrt(int x) {
        if(x==0 || x==1)
            return x;
            
        int high=x;
        int low=0;
        int middle=0;
        while(high-low>1)
        {
            middle=(high+low)/2;
            if(middle*middle>x)
                high=middle;
            else if(middle*middle<=x)
                low=middle;
        }
        return low;
    }
    

    I'm curious about why my code cannot pass the testcase"2147395599".

    My answer is -536936949, but the expected answer is 46339.

    Thanks for your reply.


  • 1
    G

    middle * middle may overflow
    middle can be up to 2147395599


  • 0
    K

    thanks a lot :)
    I've changed the type of "middle" to double and finished the program.


Log in to reply
 

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