Number of 1 Bits(LeetCode)

本文介绍计算32位无符号整数二进制表示中1的数量的三种方法,包括遍历每位、巧妙消除1位及查表法,并推荐了高效的方法。

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.


即写一个函数计算一个32位的无符号整数的二进制表达数中1的个数


方法一:常规思路,遍历32位的无符号整数的每一位,并分别进行判断,思路清晰简答,但是任何一个整数都需要循环判断32次,执行效率较低

 public int hammingWeight(int n) {
        // 原始方法,移位取与
        int num = 1;
        int count = 0;
        
        for(int i = 0; i < 32; i++)
        {
            if((n & num) != 0)
                count++;
            
            num <<= 1;
        }
        
        return count;
    }

方法一改进:即修改为每次将n右移移位,依次判断n的每一位,当n变为0的时候即可停止,不一定每一次都需要循环判断32次

public int hammingWeight(int n) {
        // 原始方法,移位取与
        int count = 0;
        
        while(n != 0)
        {
            if((n & 1) != 0)
                count++;
            
            n >>= 1;
        }
        
        return count;
    }


方法二:方法比较巧妙,每一次判断都能消除掉n最右边的一个1位,这样循环消除几次后,最终n就会变成0,即消除了几次,n中就有多少位1

此方法思路比较巧妙,而且每一次循环判断都是做的有用功,执行效率高(推荐使用此方法)

public int hammingWeight(int n) {
        // 原始方法,移位取与
        int count = 0;
        
        while(n != 0)
        {
            count++;
            n = n & (n - 1);//每一次位与运算都会将原来的那个数最右边的1置0
        }
        
        return count;
    }


方法三:查表法:可以创建一个记录16钟状态的数组表,这样每次可以判断32位中的4位上有多少个1,循环8次就可以判断完(不嫌累可以创建一个记录256中状态的数组表,这样每次可以判断32位中的8位,循环4次就可以判断完)


这个题还有其他多种解法可以解决,具体可以参考这位大神的博客:http://www.cnblogs.com/graphics/archive/2010/06/21/1752421.html

### LeetCode Problems Involving Counting the Number of 1s in Binary Representation #### Problem Description from LeetCode 191. Number of 1 Bits A task involves writing a function that receives an unsigned integer and returns the quantity of '1' bits within its binary form. The focus lies on identifying and tallying these specific bit values present in any given input number[^1]. ```python class Solution: def hammingWeight(self, n: int) -> int: count = 0 while n: count += n & 1 n >>= 1 return count ``` This Python code snippet demonstrates how to implement the solution using bitwise operations. #### Problem Description from LeetCode 338. Counting Bits Another related challenge requires generating an output list where each element represents the amount of set bits ('1') found in the binary notation for integers ranging from `0` up to a specified value `n`. This problem emphasizes creating an efficient algorithm capable of handling ranges efficiently[^4]. ```python def countBits(num): result = [0] * (num + 1) for i in range(1, num + 1): result[i] = result[i >> 1] + (i & 1) return result ``` Here, dynamic programming principles are applied alongside bitwise shifts (`>>`) and AND (`&`) operators to optimize performance during computation. #### Explanation Using Brian Kernighan Algorithm For optimizing further especially with large inputs, applying algorithms like **Brian Kernighan** offers significant advantages due to reduced iterations needed per operation compared against straightforward methods iterating through all possible positions or dividing repeatedly until reaching zero. The core idea behind this method relies upon subtracting powers-of-two corresponding only to those places holding actual ‘ones’ thereby skipping over zeroes entirely thus reducing unnecessary checks: ```python def hammingWeight(n): count = 0 while n != 0: n &= (n - 1) count += 1 return count ``` --related questions-- 1. How does the Hamming weight calculation differ between signed versus unsigned integers? 2. Can you explain why shifting right works effectively when determining counts of one-bits? 3. What optimizations exist beyond basic iteration techniques for calculating bit counts? 4. Is there any difference in implementation logic required across various programming languages supporting similar syntaxes? 5. Why might someone choose the Brian Kernighan approach over other strategies?
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值