Implement pow(x, n).题目在[这里](https://oj.leetcode.com/problems/powx-n/),二分解法如下:
~~~
class Solution {
public:
double pow(double x, int n) {
double ans;
if(n < 0){
ans = power(x, -n);
return (double)1 / ans;
}else{
return power(x, n);
}
}
double power(double x, int n) {
double ans;
if(n == 0) ans=1;
else
{ ans=power(x*x, n/2);
if(n%2==1) ans*=x;
}
return ans;
}
};
~~~
还可以这么写:
~~~
class Solution {
public:
double pow(double x, int n) {
double ans;
if(n < 0)
return (double)1 / power(x, -n);
else return power(x, n);
}
double power(double a, int n) {
double ans = 1;
while(n > 0){
if(n&1) ans *= a;
a *= a;
n >>= 1;
}
return ans;
}
};
~~~