Java: 4 lines pass all test cases


  • 1
    F
        public double myPow(double x, int n) {
            if (n == 0) return 1;
            if (n < 0) return 1 / myPow(x, - (n + 1)) / x;
            double t = myPow(x, n >> 1);
            return ((n & 1) == 1 ? x : 1) * t * t;
        }
    

  • 0
    J

    Nice solution~ Could you please explain why do you use
    1 / myPow(x, - (n + 1)) / x instead of 1 / myPow(x, -n)?

    Thx.


  • 1
    F

    @Jessica One of test cases is Integer.MIN_VALUE. It can't be '-n' directly.


Log in to reply
 

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