leetCode(32):Power of Two 分类: leetCode 2015-07-07 10:40 205人阅读 评论(0) 收藏

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

       2的幂的二进制表示中,必然只有一个“1”,且不可能为负数。

class Solution {
public:
    bool isPowerOfTwo(int n) {
        if(n<0)
        {//若为负数则直接返回
    	    return false;
        }
    	int num=0;
    	while(n)
    	{//统计1的个数
    		n=n&(n-1);
    		num++;
    	}
    	if(num==1)
    		return true;
    	return false;
    }
};


posted @ 2015-07-07 10:40  朱传林  阅读(106)  评论(0编辑  收藏  举报