参考自:《剑指Offer——名企面试官精讲典型编程题》
题目:数值的整数次方
实现函数double Power(double base, int exponent),求base的exponent次方。不得使用库函数,同时不需要考虑大数问题。
主要思路:
以下以n代替exponent(指数)
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
这样只需要log(n)次乘法运算。若n为负数,首先将n变为正数,然后再进行上述运算,最后对运算结果求倒数。同时,要注意底数为0的情况。
关键点:快速乘方,递归
时间复杂度:O(log(n))
public class PowerWithUnsignedExponent {
public static void main(String[] args) {
int base = 2;
//8.0
System.out.println(power(base, 3));
//0.125
System.out.println(power(base, -3));
//0.0
System.out.println(power(0, 3));
}
private static double power(double base, int exponent) {
if (equal(base, 0.0)) {
return 0.0;
}
if (exponent < 0) {
return 1 / powerWithExponent(base, -exponent);
} else {
return powerWithExponent(base, exponent);
}
}
private static double powerWithExponent(double base, int exponent) {
if (exponent == 0) {
return 1;
}
if (exponent == 1) {
return base;
}
//翻倍递归
double result = powerWithExponent(base, exponent >> 1);
result *= result;
//若指数为奇数,还要乘上base
if ((exponent & 0x1) == 1) {
result *= base;
}
return result;
}
private static boolean equal(double num1, double num2) {
return (num1 - num2 > -0.0000001) && (num1 - num2 < 0.0000001);
}
}