题目链接: leetcode.
简单的循环时间复杂度为 O(n),会超时
/*
301 / 304 个通过测试用例
超时 [2.00000, 2147483648]
*/
class Solution {
public:
double myPow(double x, int n) {
double ans = 1;
if(n == 0 || x == 1)
return 1;
else if(n > 0)
{
while(n--)
{
ans *= x;
}
}
else
{
while(n++)
{
ans /= x;
}
}
return ans;
}
};
大佬解释了一通快速幂 题解.
n = [bm bm-1 ……b3 b2 b1 b0]二进制
n = b0 + (2)^b1 + (2*2)^b2 + …
x^n = x^(b0) * x ^ (2^b1) * x^ ((2 *2) ^ b2) * …
/*
执行用时:0 ms, 在所有 C++ 提交中击败了100.00%的用户
内存消耗:5.9 MB, 在所有 C++ 提交中击败了73.23%的用户
*/
class Solution {
public:
double myPow(double x, int n) {
if(n == 0 || x == 1)
return 1;
double ans = 1.0;
long b = n;
if(n < 0)
{
b = -b;
x = 1 / x;
}
while(b)
{
ans *= ((b & 1)?x:1);
// cout<<b<<endl;
x *= x;
b >>= 1;
}
return ans;
}
};
x *= x;
这句折磨了我好久,要搞清楚新一个x是上一个x的平方!- n为-2147483648,-n会超出范围(
int ∈[-2147483648, 2147483647)
),所以使用long b
来存放n,-b不会溢出。