数值的整数次方(十二)
代码(已在牛客上 AC)
注意, 由于要考虑 exponent
为负数的情况, 所以 double power(double base, long n)
中的 n
是 long
类型, 这样才 -exponent
才不会越界. 之后使用递归求解最后的结果. (进阶: 如果 exponent
是小数, 那么该怎样改进?)
class Solution {
public:
double Power(double base, int exponent) {
if (exponent < 0) return 1. / power(base, -exponent);
return power(base, exponent);
}
private:
// 这里参数中使用 long 是因为担心测试用例中可能存在
// exponent=INT32_MIN, 这样 -exponent 就可能越界.
double power(double base, long n) {
if (n == 0) return 1;
double res = 1.;
double half = power(base, n / 2);
// 如果 n 为奇数, 那么结果为 half * half * base.
if (n % 2) res = half * half * base;
else res = half * half;
return res;
}
};