文章作者:Tyan
博客:noahsnail.com | CSDN | 简书
1. Description
2. Solution
- Iterative
class Solution {
public:
double myPow(double x, int n) {
double result = 1.0;
long m = labs(n);
x = n>0?x:1/x;
while(m) {
if(m & 1) {
result *= x;
}
x *= x;
m >>= 1;
}
return result;
}
};
- Recursive
class Solution {
public:
double myPow(double x, int n) {
x = n>0?x:1/x;
long m = labs(n);
return power(x, m);
}
double power(double x, long n) {
if(n == 0) {
return 1;
}
if(n % 2) {
return x * power(x * x, n / 2);
}
else {
return power(x * x, n / 2);
}
}
};