快速幂(迭代法)
迭代法求快速幂 pow(x, n).
class Solution {
public:
double multiply(double x, long long n) {
double ans = 1.0;
double base_x = x;
while (n > 0) {
if (n % 2 == 1) {
ans *= base_x;
}
base_x *= base_x;
n /= 2;
}
return ans;
}
double myPow(double x, int n) {
long long N = n;
return N >= 0 ? multiply(x, N): (1.0 / multiply(x, -(long long)N));
}
};
浙公网安备 33010602011771号