描述
实现pow这个函数
解决
利用快速幂,但是注意把右移改成 n /= 2。开始我一直用n >>= 1,但是一直超时,发现测试样例用到了最小的int整数-2147483648, 思考了觉得是,如果用 n>>= 1, 计算机会把负数转换成补码的形式,然后就会一直死循环。
class Solution {
public:
double myPow(double x, int n) {
double res = 1;
bool flag = (n >= 0 ? true : false);
n = abs(n);
while (n){
if (n & 1){
res *= x;
}
x *= x;
n /= 2;
}
return flag ? res : (1.0 / res);
}
};