首页 > 其他 > 详细

【Power of Two】cpp

时间:2015-07-22 08:05:08      阅读:145      评论:0      收藏:0      [点我收藏+]

题目:

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

代码:

class Solution {
public:
    bool isPowerOfTwo(int n) {
            if ( n<=0 ) return false;
            int countOne = 0;
            for ( int i=0; i<sizeof(n)*8 && countOne<=1; ++i )
            {
                countOne += (n>>i) & 1;
            }
            return countOne==1;
    }
};

tips:

首先的思路是bit-munipulation

检查int中有多少个1

学习了一个更简洁的(https://leetcode.com/discuss/45017/5-lines-o-1-space%26time-c-solution-no-hash

自己优化了一下 一行代码AC。

class Solution {
public:
    bool isPowerOfTwo(int n) {
            return  n<=0 ? false : !(n & (n-1));
    }
};

 

【Power of Two】cpp

原文:http://www.cnblogs.com/xbf9xbf/p/4666194.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!