码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode---Pow(x, n)

时间:2015-01-12 13:07:32      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:leetcode   位运算   

Implement pow(xn).

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


LeetCode---Pow(x, n)

标签:leetcode   位运算   

原文地址:http://blog.csdn.net/shaya118/article/details/42640157

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!