50. Pow(x, n)

Description

Implement pow(x, n).

Example 1:

Input: 2.00000, 10
Output: 1024.00000

Example 2:

Input: 2.10000, 3
Output: 9.26100

Solution

Divide & Conquer, time O(logn), space O(1)

注意避免overflow。
自顶向下分治会stack overflow,例如遇到pow(2, Integer.MIN_VALUE)。需要采用自底向上分治。

class Solution {
    public double myPow(double x, int n) {
        // convert to long to avoid overflow, say n = Integer.MIN_VALUE
        return n < 0 ? 1 / myPowLong(x, 0l - n) : myPowLong(x, n);
    }
    
    public double myPowLong(double x, long n) {
        if (n == 0) {
            return 1;
        }
        
        if (n == 1) {
            return x;
        }
        
        double value = x;
        long count = 1;
        
        while ((count << 1) <= n) {
            value *= value;
            count <<= 1;
        }
        
        return value * myPowLong(x, n - count);
    }
}

或者

class Solution {
    public double myPow(double x, int n) {
        return myPow(x, (long) n);  // in case -n overflows
    }
    
    public double myPow(double x, long n) {
        if (n < 0) {
            return 1 / myPow(x, -n);
        } else if (n == 0) {
            return 1;
        } else if (n == 1) {
            return x;
        } else if ((n & 1) == 0) {    // even
            double sub = myPow(x, n >> 1);
            return sub * sub;
        } else {                      // odd
            return x * myPow(x, n - 1);
        }
    }
}

再或者

class Solution {
    public double myPow(double x, int n) {
        return myPow(x, (long) n);  // in case -n overflows
    }
    
    public double myPow(double x, long n) {
        if (n < 0) {
            return 1 / myPow(x, -n);
        } else if (n == 0) {
            return 1;
        } else if (n == 1) {
            return x;
        } else if ((n & 1) == 0) {    // even
            return myPow(x * x, n >> 1);
        } else {                      // odd
            return x * myPow(x * x, n >> 1);
        }
    }
}

你可能感兴趣的:(50. Pow(x, n))