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