题意:
实现pow(x, n),即实数x的整数n次方。
思路:
快速幂算法。将指数表示成二进制,这时迭代生成x的1、2、4、16……次方,如果指数的二进制表示种某位为1,那么把对应x的某次方乘到答案里。
代码:
class Solution {
public:
double myPow(double x, int n) {
if (x > -1e-8 && x < 1e-8) {
return 0;
}
if (n == 0) {
return 1;
}
long long up = n;
if (up < 0) {
x = 1.0 / x;
up = -up;
}
double y = 1.0;
while (up) {
if (up & 1) {
y *= x;
}
x *= x;
up >>= 1;
}
return y;
}
};