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

231 Power of Two

时间:2015-07-07 16:59:21      阅读:148      评论:0      收藏:0      [点我收藏+]

标签:leetcode

231 Power of Two

链接:https://leetcode.com/problems/power-of-two/
问题描述:
Given an integer, write a function to determine if it is a power of two.

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

Hide Tags Math Bit Manipulation

求一个数字是不是2的幂。如果一个数字是2的幂那么在二进制标识中,一定有且仅有一个1。

class Solution {
public:
    bool isPowerOfTwo(int n) {
        int sum=0;
        if(n<0) return false;
        for(int i=0;i<32;i++)
        {
           sum+=(n&1);
           n>>=1;
        }
        if(sum==1)
            return true;
        else
            return false;
    }
};

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

231 Power of Two

标签:leetcode

原文地址:http://blog.csdn.net/efergrehbtrj/article/details/46790113

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