Pow(x, n) leetcode

Implement pow(xn).

Subscribe to see which companies asked this question

利用依次消去二进制位上的1,来进行计算

double myPow(double x, int n) {
    double ans = 1;
    unsigned long long p;
    if (n < 0) {
        p = -n;
        x = 1 / x;
    }
    else {
        p = n;
    }
    while (p) {
        if (p & 1)
            ans *= x;
        x *= x;
        p >>= 1;
    }
    return ans;
}
原文地址:https://www.cnblogs.com/sdlwlxf/p/5127015.html