Leetcode--Number of 1 Bits

 Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight).For example, the 32-bit integer ’11'  has binary representation 00000000000000000000000000001011, so the function should return 3. 
思路:首先想到的是将比特位逐个右移,然后计算1的数量

具体代码如下:
 int hammingWeight(uint32_t n) {
        int res = 0;
	while (n != 0){//当数字n不为0,或者是说当n中还有1的时候,一直循环
	    if(n %2 != 0)//判断n是否能够被2整除就是判断右移之后的n的末位是不是1,如果是1的话,计数器加1
		++res;
	    n/=2;//n右移一位
	}
	return res;
    }
还有一种相似的做法就是逐个对n的32比特位进行与的运算,然后算出1的数量
代码如下:
int hammingWeight(uint32_t n) {
        int res = 0;
        for (int i = 0; i < 32; ++i) {
            res += (n & 1);//n&1 的意思就是判断n的末位是不是1,是1的话,结果为1,不是的话结果为0,然后再累加到res中
            n = n >> 1;//n右移一位
        }
        return res;
    }
但是这还是不够快,要循环32遍才能找出所有的1,如果能有多少个1循环多少遍,就是最快的方法。
举例来说:
n = 0x110100   n-1 = 0x110011   n&(n - 1) = 0x110000 
n = 0x110000   n-1 = 0x101111   n&(n - 1) = 0x100000 
n = 0x100000   n-1 = 0x011111   n&(n - 1) = 0x0 
由上可知,n&(n-1)能够把除了n和n-1中共有的1保留,其他的全部变0.由此写出代码:
<pre name="code" class="cpp">int hammingWeight(uint32_t n) {
        int re = 0;
        int left = 0;      
<span style="white-space:pre">	</span>while(0 != n)
<span style="white-space:pre">	</span>{
    <span style="white-space:pre">	</span>     n = n&(n - 1);
    <span style="white-space:pre">	</span>     ++re;
<span style="white-space:pre">	</span>}
  }
 这样便可做到有多少1循环多少遍。 
参考文章:
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值