题目描述
实现 pow(x, n)
,即计算 x 的 n 次幂函数(即,x^n
)。不得使用库函数,同时不需要考虑大数问题。
示例
使用快速幂算法实现。
快速幂算法详解
题解
class Solution {
public:
double myPow(double x, int n) {
double res = 1;
if (n == 0) return 1.0;
int ini = n;
n = abs(n);
while (n > 0) {
if (n % 2 == 1) {
res *= x;
}
n /= 2;
x *= x;
}
if (ini > 0) {
return res;
} else {
return (double)(1 / res);
}
}
};