题目
Pow(x, n)
Implement pow(x, n).
解析
题目看似很简单,需要注意的地方在于,要考虑到n为负数和0的情况。第二,不能使用递归,要用迭代,递归会导致堆栈溢出。
如果你以为这样就好了,例如我的如下代码
class Solution {
public:
double myPowSub(double x, int n)
{
double ret = 1;
for(int i = 0; i<n; i++)
{
ret *= x;
}
return ret;
}
double myPow(double x, int n) {
if (n>=0)
{
return myPowSub(x,n);
}
else
{
return 1.0/myPowSub(x,-n);
}
}
};
你会发现凶残的超时了。
0.00001, 2147483647 这个会报错
这个时候就要思考如何改善性能了,例如二分法,把O(n)的时间复杂度降低为O(logn)
关键的是重复的计算就不要进行了,例如x *x可以保存成一个值。
代码如下
class Solution {
public:
double myPowSub(double x, int n)
{
if (n == 0)
{
return 1;
}
if (n == 1)
{
return x;
}
if (n%2 == 0)
{
double tmp = myPowSub(x,n/2);
return tmp*tmp;
}
else
{
double tmp = myPowSub(x,n/2);
return tmp*tmp*x;
}
}
double myPow(double x, int n) {
<span style="white-space:pre"> </span>if (n>0)
{
return myPowSub(x,n);
}
else
{
return 1.0/myPowSub(x,-n);
}
}
};
大神的思路跟我差不多,不过确实优化了一些,更简洁了
class Solution {
public:
double myPow(double x, int n)
{
if (n < 0)
return 1.0 / power(x, -n);
else
return power(x, n);
}
private:
double power(double x, int n)
{
if (n == 0) return 1;
double v = power(x, n / 2);
if (n % 2 == 0)
return v * v;
else
return v * v * x;
}
};