Pow(x, n)
-
n == 0
时,结果为1 -
n > 0
时,结果是x ^ n
-
否则,为上述结果的倒数
-
if n是odd({x}^{n} = {x}{frac{n}{2}} imes{x}{frac{n}{2}} imes{x} )
-
if n是even({x}^{n} = {x}{frac{n}{2}} imes{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;
}
}