Leetcode Pow(x, n)

2015-07-24 06:37:54 · 作者: · 浏览: 50

?

?

Pow(x, n)

Total Accepted: 14246 Total Submissions: 55043My Submissions

?

Implement pow(x, n).

?


?

显然是用利用快速幂,不过要注意n<0的情况。快速幂的话,可以参考我的另一篇博客 http://blog.csdn.net/asdfghjkl1993/article/details/16967897

?

?

class Solution {
public:
    double pow(double x, int n) 
    {
        double res=1;
        if(n<0)
        {
            x=1/x;
            n=-n;
        }
        while(n>0)
        {
            if(n&1)
                res=res*x;
            x=x*x;
            n>>=1;
        }
        return res;
    }
};


?