【剑指Offer】数值的整数次方

题目

实现函数double Power(double base, int exponent),求base的exponent次方。不得使用库函数,同时不需要考虑大数问题。

自以为题目简单的解法

1
2
3
4
5
6
7
8
9
10
11
public double Power(double base, int exponent) {
double result = 1;

for (int i = 1; i <= Math.abs(exponent); i++)
result *= base;

if (exponent < 0)
result = 1 / result;

return result;
}

全面又高效的解法,确保我们能拿到Offer

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public double Power(double base, int exponent) {
if (exponent == 1)
return base;
else if (exponent == 0)
return 1;

double result = Power(base, Math.abs(exponent) >> 1);

result *= result;

if ((exponent & 1) == 1)
result *= base;

if (exponent < 0)
result = 1 / result;

return result;
}