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

leetcode_Power of Two_easy

时间:2015-07-31 01:24:20      阅读:90      评论:0      收藏:0      [点我收藏+]

标签:leetcode   bit manipulation   c++   

Given an integer, write a function to determine if it is a power of two.

题目意思:判断某个数是否是2的幂。

方法:直接进行bit运算,判断是否这个数二进制位里有且仅有一个1。

class Solution {
public:
    bool isPowerOfTwo(int n) {
        int c=0;
        while(n!=0)
        {
            c+=1&n;
            if(c>1)
                return false;
            n>>=1;
        }
        if(c==1)
            return true;
        else
            return false;
    }
};



版权声明:本文为博主原创文章,未经博主允许不得转载。

leetcode_Power of Two_easy

标签:leetcode   bit manipulation   c++   

原文地址:http://blog.csdn.net/u013861066/article/details/47160163

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