题目非常简单,但需要考虑的细节
1) x = 0 或 n = 0
2) n 为正或负数
利用递归,算法复杂度为O(log(n))
代码如下:
double pow1(double x, int n){
double result = 1;
if(n==0)return 1;
if(n==1)return x;
if(n%2==0)
{
result=pow1(x,n/2);
result*=result;
}
if(n%2==1)
{
result=pow1(x,n/2);
result*=result;
result*=x;
}
return result;
}
double pow(double x, int n) {
double equal0=0.0000001;
//assert(!(abs(x)<equal0&&n==0));
if(n==0) return 1;
if(abs(x)<equal0)return 0;
bool flag=false;
if(n<0){
flag=true;
n=abs(n);
}
double result = pow1(x,n);
if(flag)
{
result=1.0/result;
}
return result;
}