[LeetCode 050] Pow(x, n)

Pow(x, n)

  • n == 0时,结果为1

  • n > 0时,结果是x ^ n

  • 否则,为上述结果的倒数

  • if n是odd\({x}^{n} = {x}{\frac{n}{2}}\times{x}{2}}\times{x} \)

  • if n是even\({x}^{n} = {x}{\frac{n}{2}}\times{x}{2}} \)

Implementation

Recursive

public class Solution {
    public double myPow(double x, int n) {
        if (n < 0) {
            x = 1 / x;
        }
        return pow(x, n);
    }

    public double pow(double x, int n) {
        if (n == 0)
            return 1;
        double factor = pow(x, n / 2);
        factor *= factor;
        if (Math.abs(n % 2) == 1)
            factor *= x;
        return factor;
    }
}

Iterative

  • 从下到上两两相乘,多余的一个乘到结果中(n代表这一层有几个数)
public class Solution {
    public double myPow(double x, int n) {
        if (n < 0) {
            x = 1 / x;
        }
        double result = 1;
        while (n != 0) {
            if (Math.abs(n % 2) == 1) {
                result = result * x;
            }
            x = x * x;
            n = n / 2;
        }
        return result;
    }
}
posted @ 2016-02-15 09:16  VicHawk  阅读(238)  评论(0编辑  收藏  举报