Implement pow(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; } };
时间: 2024-12-06 03:15:46