Implement pow(x, n).
我的做法就比较傻了。排除了所有的特殊情况(而且double一般不可以直接判断==),然后常规情况用循环来做。- -|||
直接用循环,时间复杂度就比较大。应该是用二分法来做。先计算pow(x,n/2)。然后再pow(x,n)=pow(x,n/2)*pow(x,n/2)
class Solution {
public:
double power(double x, int n){
if(n==)
return ;
double v = power(x,n/);
if(n% == )
return v *v;
else
return v* v* x;
}
double myPow(double x, int n) {
if(n<)
return 1.0 / power(x,-n);
else
return power(x,n);
}
};
#define EPSINON 0.00001
#define Max 2147483647
#define Min -2147483648
#define DBL_MAX 1.7976931348623159e+308 class Solution {
public:
double myPow(double x, int n) {
/*
three special case
*/
if(n==)
return x;
if(n==)
return 1.0;
if(abs(x)==1.00000){
if(n%==)
return 1.0;
else
return x;
} if(n>=Max){
if(abs(x)<=EPSINON)
return 0.0;
else
return DBL_MAX;
} if(n<=Min){
if(abs(x)<=EPSINON)
return DBL_MAX;
else
return 0.0;
} int size=abs(n);
double tmp=x;
for(int i=;i<=size;i++){
tmp*=x;
}
if(n>=)
return tmp;
else
return 1.0/tmp;
}
};