Pow(x, n)(x的n次幂)

http://www.lintcode.com/en/problem/powx-n/

public class Solution {
    /**
     * @param x the base number
     * @param n the power number
     * @return the result
     */
    public double myPow(double x, int n) {
        // Write your code here
        if (n == 0) {
            return 1;
        } else if (n == 1) {
            return x;
        }
        boolean isNegative = false;
        if (n < 0) {
            isNegative = true;
        }
        int k = n / 2;
        int l = n - k * 2;
        double t1 = myPow(x, Math.abs(k));
        double t2 = myPow(x, Math.abs(l));
        if (isNegative) {
            return 1 / (t1 * t1 * t2);
        } else {
            return t1 * t1 * t2;
        }
    }
}

你可能感兴趣的:(Pow(x, n)(x的n次幂))