题目
实现函数double Power(double base, int exponent),求base的 exponent次方。
不得使用库函数,同时不需要考虑大数问题。
只要输出结果与答案的绝对误差不超过 10−210−2 即视为正确。
注意:
不会出现底数和指数同为0的情况
当底数为0时,指数一定为正
题解:
用快速幂做,注意当指数是负数时,我们需要先取指数的绝对值,最后将乘积的倒数作为答案。
时间复杂度:O(logn)
代码:
class Solution {
public:
double myPow(double x, int n) {
typedef long long LL;
bool is_minus = n < 0;
double res = 1;
for (LL k = abs(LL(n)); k; k >>= 1) {
if (k & 1) res *= x;
x *= x;
}
if (is_minus) res = 1 / res;
return res;
}
};