题目描述如下:
Implement pow(x, n).
非常简单的一句话。
但這其中有一些坑。
就是INT_MIN的相反数,会溢出。
所以现将输入的参数强行转换为long防止这个问题。
代码如下:
double myPow(double x, int n) {
if(x==0)
return 0;
long temp=n;
if(temp<0){
temp=-temp;
x=1/x;
}
if(n==0){
return 1;
}
if(temp/2>0){
double p=x*x;
if(n%2)
return myPow(p, temp/2)*x;
else
return myPow(p, temp/2);
}
else
return x;
}