力扣
重点学习快速幂算法!
class Solution {
public double myPow(double x, int n) {
long N = n;
return N >= 0 ? quickMul(x, N) : 1.0 / quickMul(x, -N);
}
public double quickMul(double x, long N) {
if (N == 0) {
return 1.0;
}
double y = quickMul(x, N / 2);
return N % 2 == 0 ? y * y : y * y * x;
}
}
Solution1:基本算法
累乘,时间复杂度为O(n)
要考虑全部情况:指数 < 0, == 0 和 > 0.
注意在 if…else if的语句中最后一个最好写成else,否则在牛客网上编译报错
class Solution {
public:
double Power(double base, int exponent) {
double res=1.0;
if(exponent>0){
while(exponent-->0)
res*=base;
return res;
}
else if(exponent == 0){
return res;
}
else {
int abs_exp=-exponent;
while(abs_exp-->0)
res*=base;
return (1.0/res);
}
}
};
Solution2:
优化版的算法:时间复杂度
O
(
l
o
g
n
)
O(log n)
O(logn)
当n为偶数:
a
n
=
a
n
/
2
∗
a
n
/
2
a^n =a^{n/2}*a^{n/2}
an=an/2∗an/2
当n为奇数:
a
n
=
a
(
n
−
1
)
/
2
∗
a
(
n
−
1
)
/
2
∗
a
a^n = a^{(n-1)/2} * a^{(n-1)/2} * a
an=a(n−1)/2∗a(n−1)/2∗a
书上的代码有坑,肾重啊肾重!
class Solution {
public:
double Power(double base, int exponent) {
int abs_exp = abs(exponent);
if (abs_exp == 0)
return 1;
else if (abs_exp == 1)
return base;
double res = Power(base, abs_exp/2);
res *= res;
if (abs_exp & 1)
res *= base;
if (exponent < 0)
res = 1/res;
return res;
}
};