Implement pow(x, n).
下面的算法,满足small judge, 但是 large judege超出时间限制
class Solution {
public:
double pow(double x, int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (n == 0)
return (double)1;
if (n == 1)
return x;
bool bIsNegative = n>0? false:true;
int N = abs(n);
double midleVal = x;
int i = 1;
while (i*2 <= n)
{
i = i << 1;
midleVal = midleVal*midleVal;
}
if (i == n)
return midleVal;
N = N - i;
midleVal = midleVal * pow(x, N);
if (bIsNegative)
{
return 1/midleVal;
}
return midleVal;
}
};
改进算法
class Solution {
//31
// 2,4,8,16, 2,4,8, 2,4, 2, 1
double pow2(double x, int n) {
if (n == 1)
return x;
double remain = n%2;
double ret = pow2(x, n/2);
if (remain)
{
return ret*ret*pow2(x, remain);
}
return ret*ret;
}
public:
double pow(double x, int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (n == 0)
return (double)1;
if (n == 1)
return x;
if (x == 1)
return 1;
bool bNegative = n>0?false:true;
double ret = pow2(x, abs(n));
if (bNegative)
return 1.0/ret;
return ret;
}
};