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.


分析与思路


方法一


采用最直接的办法,依次移位并与 0x1 做与操作。

代码:

int hammingWeight(uint32_t n) {
	int cnt=0;
	while(n)
	{
		if((n&0x1) == 1)
			cnt++;
		n=n>>1;
	}
	return cnt;
}


方法二


按照题目给出的提示的办法,hamming weight算法。在 Hamming Weight算法分析中有详细的分析。

代码:

class Solution {
public:
    int hammingWeight(uint32_t x) {  
        const uint32_t m1  = 0x55555555; //binary: 0101...  
        const uint32_t m2  = 0x33333333; //binary: 00110011..  
        const uint32_t m4  = 0x0f0f0f0f; //binary:  4 zeros,  4 ones ...  
        const uint32_t h01 = 0x01010101; //the sum of 256 to the power of 0,1,2,3... 
        x -= (x >> 1) & m1;             //put count of each 2 bits into those 2 bits  
        x = (x & m2) + ((x >> 2) & m2); //put count of each 4 bits into those 4 bits   
        x = (x + (x >> 4)) & m4;        //put count of each 8 bits into those 8 bits   
        return (x * h01)>>56;  //returns left 8 bits of x + (x<<8) + (x<<16) + (x<<24) + ...   
    }  
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值