leetcode 191. Number of 1 Bits(bit中1的个数)

本文介绍了一种高效算法,用于计算32位整型数中1的比特位数量,即Hamming权重。该算法通过巧妙的位操作减少计算步骤,实现了快速统计。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Write a function that takes an unsigned integer and returns the number of ‘1’ bits it has (also known as the Hamming weight).

Note:

Note that in some languages, such as Java, there is no unsigned integer type. In this case, the input will be given as a signed integer type. It should not affect your implementation, as the integer’s internal binary representation is the same, whether it is signed or unsigned.
In Java, the compiler represents the signed integers using 2’s complement notation. Therefore, in Example 3, the input represents the signed integer. -3.

Example 1:

Input: n = 00000000000000000000000000001011
Output: 3
Explanation: The input binary string 00000000000000000000000000001011 has a total of three ‘1’ bits.
Example 2:

Input: n = 00000000000000000000000010000000
Output: 1
Explanation: The input binary string 00000000000000000000000010000000 has a total of one ‘1’ bit.

Hamming距离,input是32位整型,统计其中bit位为1的个数。

思路:
有个著名的并行统计bit为1的算法,
先是相邻2位,然后4位,8位,具体参考并行bit count算法

    public int hammingWeight(int n) {
        n = n - ((n >> 1) & 0x55555555);               
        n = (n & 0x33333333) + ((n >> 2) & 0x33333333); 
        int c = ((n + (n >> 4) & 0xF0F0F0F) * 0x1010101) >> 24;
        
        return c;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝羽飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值