[Problem]
Implement pow( x, n).
[Solution]
Implement pow( x, n).
[Solution]
class Solution {说明:版权所有,转载请注明出处。 Coder007的博客
public:
double pow(double x, int n) {
// Note: The Solution object is instantiated only once and is reused by each test case.
// special cases
if(n == 0)return 1;
if(fabs(x - 0) < 0.0000000001)return 0;
// x == 1
if(fabs(x - 1) < 0.0000000001)return 1;
// x == -1
if(fabs(x + 1) < 0.0000000001){
if(n % 2 == 0)
return 1;
else
return -1;
}
// x < 0
if(x < 0){
if(n % 2 == 0){
return pow(-x, n);
}
else{
return -pow(-x, n);
}
}
// n < 0
if(n < 0){
return 1/pow(x, -n);
}
if(n == 1){
return x;
}
// n is even
if(n % 2 == 0){
double half = pow(x, n/2);
return half * half;
}
else{
double half = pow(x, n/2);
return half * half * x;
}
}
};