[Bit Operation-Simple] 191. Number of Bit 1

[Title]
Write a function, the input is an unsigned integer (in the form of a binary string), and returns the number of digits in the binary expression whose digits are '1' (also known as Hamming weight).
[Tips]
Please note that in some languages ​​(such as Java), there is no unsigned integer type. In this case, both input and output will be designated as signed integer types, and should not affect your implementation, because the internal binary representation is the same regardless of whether the integer 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 a signed integer -3.
Advanced
If you call this function multiple times, how would you optimize your algorithm
[Example 1]
Input: 00000000000000000000000000001011
Output: 3
Explanation: In the input binary string 00000000000000000000000000001011, there are three bits as '1'.
[Example 2]
Input: 00000000000000000000000010000000
Output: 1
Explanation: In the input binary string 00000000000000000000000010000000, a total of one bit is '1'.
[Example 3]
Input: 11111111111111111111111111111101
Output: 31
Explanation: In the input binary string 11111111111111111111111111111101, a total of 31 bits are '1'.
prompt:
The input must be a binary string of length 32.
[Code]
[Python]
Because this question has the same meaning as my last blog, so I won’t repeat it here, only one solution is given. For the other five solutions, please see: "[Bit Operation-Simple] Sword Finger Offer 15. The number of 1 in binary (6 solutions + expansion questions have not been written yet)"
Insert picture description here

class Solution:
    def hammingWeight(self, n: int) -> int:
        cnt=0
        while n:
            cnt+=1
            n&=n-1
        return cnt

Guess you like

Origin blog.csdn.net/kz_java/article/details/115057769