Implement pow(x, n).
方法一:直接硬解,排除INT_MIN和INT_MAX的情况
class Solution {
public:
double myPow(double x, int n)
{
double res = 1;
if (n == INT_MIN)
{
if (x == 1) return x;
else if (x == -1) return -x;
else return 0;
}
else if (n == INT_MAX)
{
if (x == 1 || x == -1) return x;
else return 0;
}
else if(0 == n)
return 1;
else
if(x==0)
return 0;
else if(1==x)
return 1;
else
{
for(int i = 0; i < fabs(n); ++i)
res*=x;
return n > 0 ? res : 1/res;
}
}
};
方法二:用递归方法求n个x的乘积,注意考虑n的正负号,时间复杂度为O(n)
class Solution {
public:
double myPow(double x, int n)
{
if(0==n)
return 1;
else if(n>0)
return x*myPow(x,n-1);
else
if(n == INT_MIN)
return 1/(myPow(x,INT_MAX)*x);
else
return 1/myPow(x,-n);
}
};
但是这个程序通不过,应该是迭代次数太多,超时了。
方法三:考虑到n个x相乘式子的对称关系,可以对上述方法进行改进,从而得到一种时间复杂度为O(logn)的方法,递归关系可以表示为pow(x,n) = pow(x,n/2)*pow(x,n-n/2)
class Solution {
public:
double myPow(double x, int n)
{
if(n == 0)
return 1;
else if(n<0)
if(n == INT_MIN)
return 1/(myPow(x,INT_MAX)*x);
else
return 1/myPow(x,-n);
double half=myPow(x,n>>1);
if(n%2==0)
return half*half;
else
return half*half*x;
}
};
方法四:在discuss里看到的,不用考虑特殊情况,时间复杂度也是O(logN)
class Solution {
public:
double myPow(double x, int n)
{
if (n == 1) return x;
else if (n == 0) return 1;
else if (n == -1) return 1 / x;
double res = myPow(x, n / 2);
if (fabs(res) < 0.00001) //if the result is smaller than 0.00001,make it 0.
res = 0;
if (n % 2 == 0)
return res * res;
else
return res * myPow(x, n / 2 + n % 2);
}
};
方法五:Consider the binary representation of n. For example, if it is “10001011”, then x^n = x^(1+2+8+128) = x^1 * x^2 * x^8 * x^128. Thus, we don’t want to loop n times to calculate x^n. To speed up, we loop through each bit, if the i-th bit is 1, then we add x^(1 << i) to the result. Since (1 << i) is a power of 2, x^(1<<(i+1)) = square(x^(1<
class Solution {
public:
double myPow(double x, int n)
{
if(n == 0)
return 1;
else if(n<0)
if(n == INT_MIN)
return 1/(myPow(x,INT_MAX)*x);
else
return 1/myPow(x,-n);
double res = 1.0;
for(;n>0;x *= x,n=n>>1)
{
if(n&1>0)
res *= x;
}
return res;
}
};