Original question:
Implement POW (X,N).
Idea: recursive Calculation of pow.
class Solution {public: double pow(double x, int n) { long long int mid = n/2; int d = n%2; if(n==0) return 1; if(n==1) return x; if(d==1) return pow(x, (n/2)+1) * pow(x, n/2); else return pow(x, n/2) * pow(x, n/2); }};
Timeout at the boundary value.
INT-2147483648 ~ + 2147483647 (4 bytes)
class Solution {public: double pow(double x, int n) { long long num = n; if(num==0) return 1.0; if(num==1) return x; if(num<0) return 1.0/pow(x, -num); double half = pow(x,num>>1); if(num%2==0) return half*half; else return half*half*x; }};
If n is a negative value, the overflow occurs after negative values are obtained. Re
class Solution {public: double pow(double x, int n) { if(n==0) return 1.0; if(n==1) return x; if(n<0 && n!=INT_MIN) return 1.0/pow(x, -n); if(n==INT_MIN) return 1.0/(pow(x, INT_MAX)*x); double half = pow(x,n>>1); if(n%2==0) return half*half; else return half*half*x; }};
Consider the minimum int_min, that is, the-2147483648 take negative will overflow, so special processing is required.
AC