[Question]
Calculate Power(X, N).
[Analysis]
Power(X, N) = Power(X, N/2) * Power(X,N/2) if N is even;
Power(X, N) = Power(X, N/2) * Power(X,N/2) * X if N is odd;
There are corner cases, when N is negative or X is negative, to consider.
[Solution]
class Solution {
public:
double power(double x, int n) {
if (n==0) return 1;
if (n==1) return x;
double tmp = power(x, n/2);
if ( (n & 0x0001) ==0 )
return (tmp * tmp);
else
return (tmp * tmp * x );
}
double pow(double x, int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
bool rev=false, neg=false;
if (n<0) {
n= -n;
rev = true;
}
if (x<0 && n & 0x0001) {
x = -x;
neg = true;
}
double rslt = power(x, n);
if (rev) rslt = 1/rslt;
if (neg) rslt = -rslt;
return rslt;
}
};
No comments:
Post a Comment