191.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.

我的解答:

class Solution {
public:
    int hammingWeight(uint32_t n) {
        int count = 0;
    for (int i = 0; i < 32; i++)
    {
        count += n&0x01;
        n=n >> 1;

     }
    return count;
    }
};

解释:拿到这道题很自然就想到通过移位来计算这里面有多少个1。通过32次与0x01提取最右边的数,看是不是1.
看别人的想法是通过与减一位的数来来计算的。如下

int hammingWeight(uint32_t n) {
    int count = 0;

    while (n) {
        n &= (n - 1);
        count++;
    }

    return count;
}

解释:
每次n减1,那么原来的n的最右边一个1就变为0,该1右边的所有0变为1.原n与该n-1与了之后,那么最右1及右边的所有位都为0.如
If n = 00101100, then n - 1 = 00101011, so n & (n - 1) = 00101100 & 00101011 = 00101000. Count = 1.

If n = 00101000, then n - 1 = 00100111, so n & (n - 1) = 00101000 & 00100111 = 00100000. Count = 2.

If n = 00100000, then n - 1 = 00011111, so n & (n - 1) = 00100000 & 00011111 = 00000000. Count = 3.

然后循环的次数不用32次,只要循环“1”的个数就够了,因为是判断n是否为0的。n为0即结束

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值