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;
}

 

posted @ 2016-01-13 13:36  sdlwlxf  阅读(115)  评论(0编辑  收藏  举报