Daily Algorithm----191. Number of Bit 1----2023/01/05

1. Question description

Write a function that takes an unsigned integer (as a binary string) and returns the number of '1' digits in its binary expression (also known as the Hamming weight).

Tip:
Please note that in some languages ​​(such as Java), there is no unsigned integer type. In this case, both the input and output will be specified as signed integer types, and this should not affect your implementation since the internal binary representation of the integer is the same regardless of whether it is signed or unsigned.
In Java, the compiler uses two's complement notation to represent signed integers. Therefore, in Example 3 above, the input represents the signed integer -3.

Source: LeetCode
Link: https://leetcode.cn/problems/number-of-1-bits
The copyright belongs to LeetCode Network. For commercial reprinting, please contact the official authorizer. For non-commercial reprinting, please indicate the source.

2. Example

示例 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
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

3. Ideas

Traverse and divide by 2 to get the mantissa, determine whether it is 1, accumulate it to 1, divide the original number by 2, and get the final value.

4. Problems encountered

none

5. Specific implementation code

func hammingWeight(num uint32) int {
    
    
    count :=0 
    for i:=0;i<32;i++{
    
    
        target := num%2
        if target == 1{
    
    
            count ++
        }
        num = num /2
    }
    return count
}

6. Official solution

Bit operation optimization

func hammingWeight(num uint32) (ones int) {
    
    
    for ; num > 0; num &= num - 1 {
    
    
        ones++
    }
    return
}

Principle: n&(n-1)There will always be a change of 1=>0, so recording the number of changes can get the number of 1's.

Author: LeetCode-Solution
Link: https://leetcode.cn/problems/number-of-1-bits/solution/wei-1de-ge-shu-by-leetcode-solution-jnwf/
Source: LeetCode
Copyright belongs to the author. For commercial reprinting, please contact the author for authorization. For non-commercial reprinting, please indicate the source.

7 Source of question

Link: link


Another day of being defeated by bit operations. ------swrici

Guess you like

Origin blog.csdn.net/Srwici/article/details/128571905