Leetcode_191_Number of 1 Bits

本文介绍如何使用Java内置库计算无符号整数的二进制表示中1的数量,包括代码实现和解释。

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

本文是在学习中的总结,欢迎转载但请注明出处:http://blog.youkuaiyun.com/pistolove/article/details/44486547


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.


思路:

(1)题意为给定一个无符号数,返回其对应二进制数中1的个数。

(2)该题主要考察进制的转换操作。java中没有无符号数字(为什么没有可以百度下)。无符号数即给定的数都是非负数。这样我们可以通过java自带类库中的Integer.toBinaryString(value)将指定整数专为二进制数,然后求得二进制数中包含1的个数即可。详情见下方代码。

(3)希望本文对你有所帮助。


算法代码实现如下:

	/**
	 * @param liqq 直接用类库
	 */
	public int hammingWeight(int value) {
		int count = 0;
		String binaryString = Integer.toBinaryString(value);
		for (int i = 0; i < binaryString.length(); i++) {
			char charAt = binaryString.charAt(i);
			if (charAt == '1') {
				count++;
			}
		}
		return count;
	}
	/**
	 * @param liqq 简化类库中toBinaryString方法的使用
	 */
	// you need to treat n as an unsigned value
	public int hammingWeight(int value) {
		int count = 0;
		// String binaryString = Integer.toBinaryString(value);
		char[] digits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
				'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
				'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
				'y', 'z' };
		char[] buf = new char[32];
		int charPos = 32;
		int radix = 2;
		int mask = 1;
		do {
			buf[--charPos] = digits[value & 1];
			value >>>= 1;
		} while (value != 0);

		String binaryString = new String(buf, charPos, (32 - charPos));

		for (int i = 0; i < binaryString.length(); i++) {
			char charAt = binaryString.charAt(i);
			if (charAt == '1') {
				count++;
			}
		}

		return count;
	}

### 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?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值