原题链接 https://leetcode.com/problems/powx-n/
Implement pow(x, n).
以前在算法书中看到过一个,将指数n写成2进制的情况。
比如2^5 = 2^101 = 2^3 * 2^1
class Solution {
public:
double myPow(double x, int n) {
double ans = 1;
bool flag = true;
long long p = n;
if (p < 0)flag = false, p = abs(p);
while (p)
{
if (p & 1)ans *= x;
x *= x;
p >>= 1;
}
return flag ? ans : 1.0 / ans;
}
};