Implement pow(x, n).
Recursive solution is easier to understand. It uses the divide-and-conquer approach, which also runs in time.
The formula is shown below:
class Solution {
public:
double pow(double x, int n) {
if (n == 0) return 1.0;
// Compute x^{n/2} and store the result into a temporary
// variable to avoid unnecessary computing
double half = pow(x, n / 2);
if (n % 2 == 0)
return half * half;
else if (n > 0)
return half * half * x;
else
return half * half / x;
}
};
本文介绍了一种使用递归实现快速幂运算的方法,该方法采用分治策略,通过计算x^(n/2)来减少计算量,并能有效处理正负指数的情况。
292

被折叠的 条评论
为什么被折叠?



