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

Example 1:

Input: 11
Output: 3
Explanation: Integer 11 has binary representation 00000000000000000000000000001011 

Example 2:

Input: 128
Output: 1
Explanation: Integer 128 has binary representation 00000000000000000000000010000000

简述:

给一个无符号整型数,求它的二进制形式中1的数量。

 

解题思路:


思路1:

通过位操作解题。将n与1进行位与操作可以判断n的最后一位二进制位是否为1,不断将n与1进行位与操作,统计1的数量。

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

 

思路2:

观察以下几组数据:

n:  1101       n-1:  1100        n&(n-1):  1100

n:  1110       n-1:  1101        n&(n-1):  1100   

n:  1100       n-1:  1011        n&(n-1):  1000 

不难发现,利用n&(n-1)可以将n二进制形式中最末尾的1置0。

因此,不断的进行n&(n-1)的操作,直到n为0,统计操作次数即为1的个数。

    int hammingWeight(uint32_t n) {
        int num = 0;
        while(n) {
            ++num;
            
            n = n&(n-1);
        }
        
        return num;
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值