现 pow(x, n) ,即计算 x 的 n 次幂函数
leecode 讲解记录
方法一:暴力法
思路
只需模拟将 x 相乘 n 次的过程。
class Solution {
public double myPow(double x, int n) {
long N = n;
if (N < 0) {
x = 1 / x;
N = -N;
}
double ans = 1;
for (long i = 0; i < N; i++)
ans = ans * x;
return ans;
}
};
复杂度分析
时间复杂度: O(n)。我们将 x 相乘 n 次。
空间复杂度:O(1)O(1)。我们需要一个变量来存储 x 的最终结果。
方法二:递归快速幂算法
class Solution {
private double fastPow(double x, long n) {
if (n == 0) {
return 1.0;
}
double half = fastPow(x, n / 2);
if (n % 2 == 0) {
return half * half;
} else {
return half * half * x;
}
}
public double myPow(double x, int n) {
long N = n;
if (N < 0) {
x = 1 / x;
N = -N;
}
return fastPow(x, N);
}
};
方法三:迭代快速幂算法
class Solution {
public double myPow(double x, int n) {
long N = n;
if (N < 0) {
x = 1 / x;
N = -N;
}
double ans = 1;
double current_product = x;
for (long i = N; i > 0; i /= 2) {
if ((i % 2) == 1) {
ans = ans * current_product;
}
current_product = current_product * current_product;
}
return ans;
}
};