计算x的n次方
思路1:
暴力,依次乘以x,乘n次, 复杂度log(N),最后还ac不通过,貌似中间有溢出
Runtime Error Message:
AddressSanitizer: stack-overflow on address 0x7ffc6c846ff8 (pc 0x000000406e3b bp 0x7ffc6c847010 sp 0x7ffc6c847000 T0)
Last executed input:
0.00001
2147483647
思路2:
使用分治思想
如果n为偶数:pow(x, n) = pow(x, n/2) * pow(x, n/2)
如果n为奇数:pow(x, n) = pow(x, n/2) * pow(x, n/2) * x
代码如下:
class Solution {
public:
double myPow(double x, int n) {
if (n < 0)
return 1 / myPowPassive(x, -1 * (long)(n));
else
return myPowPassive(x, n);
}
private:
double myPowPassive(double x, long n) {
double tmpResult = 0.0;
if (0 == n)
return 1.0;
tmpResult = myPowPassive(x, n >> 1);
if (0 == n % 2)
return tmpResult * tmpResult;
else
return tmpResult * tmpResult * x;
}
};
注意另外一个坑,如果n为-2147483648,则-1 * -2147483648 = 2147483648是会超出int的区间范围,所以需要先转换为long类型