问题描述:
实现 pow(x, n) ,即计算 x 的 n 次幂函数。
示例 1:
输入: 2.00000, 10
输出: 1024.00000
示例 2:
输入: 2.10000, 3
输出: 9.26100
示例 3:
输入: 2.00000, -2
输出: 0.25000
解释: 2-2 = 1/22 = 1/4 = 0.25
补充示例4:
输入: 0.00001, 2147483647
输出: 一般方法不能搞定。
说明:
-100.0 < x < 100.0
n 是 32 位有符号整数,其数值范围是 [−231, 231 − 1] 。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/powx-n
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
执行结果:
代码描述:
- 方法一:暴力求解。在res上直接乘以n个x,但是却不能满足用例:0.00001 2147483647
class Solution {
public:
double myPow(double x, int n) {
if(n < 0)
{
x = 1/x;
n = -n;
}
double res = 1.0;
for(int i = 0; i < n; ++i)
{
res *= x;
}
return res;
}
};
- 方法二:迭代快速幂。当 2的次幂为5时,res 先乘以一个2, x本身乘以x,就变为x^2。x^2 * x^2 就是 x^4。不用x乘以4次。
class Solution {
public:
double myPow(double x, int n) {
if(n == 0) return 1.0;
double res = 1.0;
for(int i = n; i != 0; i/=2)
{
if(i % 2 != 0) // 奇数时,结果先乘以一个x
res *= x;
x *= x; // 偶数时,x本身自乘
}
return n < 0? 1/res:res; // 判断分子还是分母
}
};
- 方法三:快速递归
class Solution {
public:
double myPow(double x, int n) {
long long N = n; // 一定要先进行类型转换
if(N < 0)
{
x = 1/x;
N = -N;
}
return fast(x, N);
}
double fast(double x, long int N)
{
if(N == 0) return 1.0;
double half = fast(x, N/2);
if(N%2 == 1)
{
return half * half*x;
}
else
{
return half * half;
}
}
};
错误原因,是int 型不能承受 -2147483648这个数字
Line 8: Char 17: runtime error: negation of -2147483648 cannot be represented
in type 'int'; cast to an unsigned type to negate this value to itself (solution.cpp)