Java 20ms solution. Handles all corner cases.


  • 0
    W
       public double myPow(double x, int n) {
            if (n < 0) {
                return 1 / powerHelper(x, n);
            } else {
                return powerHelper(x, n);
            }
        }
         
        private double powerHelper(double x, int n) {
            if (n == 0) return 1;
            if (n == 1) return x;
            double temp = powerHelper(x, n/2);
            if (n % 2 == 0) {
                return temp * temp;
            } else {
                return temp * temp * x;
            }
        }
    

Log in to reply
 

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