实现 pow(x, n)
,即计算 x
的 n
次幂函数(即,x^n
)。
示例 1:
输入:x = 2.00000, n = 10
输出:1024.00000
示例 2:
输入:x = 2.10000, n = 3
输出:9.26100
示例 3:
输入:x = 2.00000, n = -2
输出:0.25000
解释:2-2 = 1/22 = 1/4 = 0.25
提示:
-100.0 < x < 100.0
-2^31 <= n <= 2^31-1
-10^4 <= xn <= 10^4
解答
快速幂:
class Solution {
public:
double myPow(double x, int n) {
bool flag = (n < 0);
if(flag && x == 0)
return 0;
unsigned int un = abs(n);
auto temp = helper(x, un);
if(flag)
temp = 1 / temp;
return temp;
}
double helper(double x, unsigned int n) {
if(n == 0)
return 1;
auto temp = helper(x, (n >> 1));
temp *= temp;
if(n & 1)
temp *= x;
return temp;
}
};