您的位置:首页 > 其它

[LeetCode 050] Pow(x, n)

2016-02-15 09:16 225 查看

Pow(x, n)

n == 0
时,结果为1

n > 0
时,结果是
x ^ n


否则,为上述结果的倒数

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

if n是even\({x}^{n} = {x}^{\frac{n}{2}}\times{x}^{\frac{n}{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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: