O(lgn) recursive Java solution


  • 0
    G
    public class Solution {
        private double pow (double x, int n) {
            if (n == 0) return 1;
            if (n == 1) return x;
            double tmp, ret;
            if (n % 2 == 0) {
                tmp = myPow(x, n / 2);
                ret = tmp * tmp;
            } else {
                tmp = myPow(x, (n - 1) / 2);
                ret = tmp * tmp * x;
            }
            return ret;
        }
        public double myPow(double x, int n) {
            if (x == 0 && n < 0) return Double.POSITIVE_INFINITY;
            if (x == 0 || x == 1) return x;
            if (n < 0) {
                if (n == Integer.MIN_VALUE) {
                    return pow(1 / x / x, -(n + 1));
                } else {
                    return pow(1 / x, -n);
                }
            }
            return pow(x, n);
        }
    }
    

Log in to reply
 

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