Pow(x, n)
Implement pow(x, n).
实现X的n次方
思路
拿到这个题我就笑了,这么简单,来个for循环撒
于是我就傻了
一点不简单陷阱
1. n位负数
2. 时间复杂度,真的需要n次循环吗
并不!!!!
测试用例
input | output | expected |
---|---|---|
2.00000 -2147483648 | inf | 0.000 |
1.00000 -2147483648 | runtime error | 1.000 |
x是1的时候,就不用循环了,浪费时间哇
然后就是无穷怎么办
原因就是
Because INT_MAX is 2147483647 , when n is -2147483648 , -n is also -2147483648.
So your first code will recurse indefinitely then cause stack overflows.
所以就是因为n是-2147483648时 -n也是负的
代码1
为了解决上述问题,最简单的方案,设置个long long int N,显式转换就OK
class Solution {
private:
double BinaryPow(double x,long long int n)
{
if(n==1)
return x;
else if(n==0)
return 1;
if(n%2 == 0)
{
double temp = myPow(x, n/2);
return temp*temp;
}
else
{
double temp = myPow(x, (n-1)/2);
return temp*temp*x;
}
}
public:
double myPow(double x, int n) {
long long int N = (long long int )n;
if(x==0||x==1||n==1)
return x;
if(n==0)
return 1;
if(n>0)
return BinaryPow(x,N);
else
return BinaryPow((1.0/x),-N);
}
};
代码2
这个就是先除2了,然后再在奇数情况下,变为负
所以这样n就是先变小了
class Solution {
public:
double myPow(double x, int n) {
float r;
if(n==0) return 1.0;
if(n==1) return x;
if(n%2 == 0) {
r = myPow(x, n/2);
return r*r;
}
else {
if (n < 0) {
r = myPow(x, -n/2);
return 1 / (x * r * r);
} else {
r = myPow(x, n/2);
return x * r * r;
}
}
}
};