Implement pow(x, n).
Subscribe to see which companies asked this question
class Solution {
public:
double myPow(double x, int n) {
double ans = 1.0;
double temp = x;
bool flag = false;
long long cnt = n;
if(cnt == 0) return 1.0;
if(cnt < 0) {
flag = true;
cnt = -cnt;
}
while(cnt > 0) {
if(cnt & 1) {
ans *= temp;
}
temp *= temp;
cnt = cnt >> 1;
}
return flag==true?1.0/ans:ans;
}
};
本文介绍了一种使用快速幂法高效实现pow函数的方法。该方法适用于整数指数的情况,并通过位运算加速计算过程。文章提供了C++实现的示例代码。
882

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



