Last executed input: 1.00000, -2147483648, "Time Limit Exceeded" accurs, and why?


  • 0
    H
    public double pow(double x, int n) {
        if (n < 0) {
            n = -n;
            x = 1/x;
        }
        
        double result = 1;
        // And for Last executed input:	1.00000, -2147483648, "Time Limit Exceeded" accurs
        while (true) {
            int j = n&1;
            n = n>>1;
            if (j == 1) result *= x;
            if (n == 0) break;
            x = x*x;
        }
        return result;
    }

  • 0
    B

    This is because n == 0 never satisfies in your while loop. And the reason for that is when you right shift a number, the MSB is 'not' filled with '0', it is filled with the original MSB bit.


  • 0
    H

    Thank you! You are right. When n = -2147483648, the -n is still -2147483648. So the MSB is 'not' filled with '0'.


Log in to reply
 

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