数值的整数次方

Desicription

给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
private:
double QuickPower(double base, int exponent) {
double res = 1.0;
if(exponent < 0) {
base = 1.0 / base;
exponent = -exponent;
}
while(exponent) {
if(exponent & 1) {
res *= base;
}
base *= base;
exponent >>= 1;
}
return res;
}
public:
double Power(double base, int exponent) {
return QuickPower(base, exponent);
}
};