leetcode 191. Number of 1 Bits 位1的个数(简单)

一、题目大意

编写一个函数,输入是一个无符号整数(以二进制串的形式),返回其二进制表达式中数字位数为 ‘1’ 的个数(也被称为汉明重量)。

提示:

请注意,在某些语言(如 Java)中,没有无符号整数类型。在这种情况下,输入和输出都将被指定为有符号整数类型,并且不应影响您的实现,因为无论整数是有符号的还是无符号的,其内部的二进制表示形式都是相同的。
在 Java 中,编译器使用二进制补码记法来表示有符号整数。因此,在上面的 示例 3 中,输入表示有符号整数 -3。

示例 1:

输入:00000000000000000000000000001011

输出:3

解释:输入的二进制串 00000000000000000000000000001011 中,共有三位为 ‘1’。

示例 2:

输入:00000000000000000000000010000000

输出:1

解释:输入的二进制串 00000000000000000000000010000000 中,共有一位为 ‘1’。

示例 3:

输入:11111111111111111111111111111101

输出:31

解释:输入的二进制串 11111111111111111111111111111101 中,共有 31 位为 ‘1’。

提示:

  • 输入必须是长度为 32 的 二进制串 。

进阶:

  • 如果多次调用这个函数,你将如何优化你的算法?

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/number-of-1-bits
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

二、解题思路

思路1:n & 1如果为1,ans=ans+1,然后再n向右移一位,直到n=0,返回ans。注意:因为是Java实现所以要用for

思路2:先判断如果n!=0,ans++,令n = n&(n-1),循环直到n=0,返回ans。参考别人的思路,没看懂

三、解题方法

3.1 Java实现 - 思路1

public class Solution2 {
    // you need to treat n as an unsigned value
    public int hammingWeight(int n) {
        int ans = 0;
        for (int i = 0; i < 32; i++) {
            ans += n & 1;
            n >>= 1;
        }
        return ans;
    }
}

3.2 Java实现 - 思路2

public class Solution {
    // you need to treat n as an unsigned value
    public int hammingWeight(int n) {
        int ans = 0;
        while (n != 0) {
            ans++;
            n = n & (n - 1);
        }
        return ans;
    }
}

四、总结小记

  • 2011/10/24 有些东西想不明白,就埋藏心底,发酵一会
### 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、付费专栏及课程。

余额充值