leetCode(32):Power of Two

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 @ 2017-06-15 11:17  yxysuanfa  阅读(114)  评论(0编辑  收藏  举报