[Leetcode]50. Pow(x, n)
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==0) return 1; double v = power(x,n/2); if(n%2 == 0) return v *v; else return v* v* x; } double myPow(double x, int n) { if(n<0) 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==1) return x; if(n==0) return 1.0; if(abs(x)==1.00000){ if(n%2==0) 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=2;i<=size;i++){ tmp*=x; } if(n>=0) return tmp; else return 1.0/tmp; } };