Python brush question record - Jianzhi Offer 15. The number of 1 in binary

topic:

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

Are you still using the bin(n).count("1") interface, why not look at other methods.

Method 1:
Use AND operation and right shift, start the binary number from the far right, and perform AND operation with 1 bit by bit.
0&1=0, 1&1=1, the cumulative result is the number of the last 1

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

Method 2:
In method 1, as many times as there are binary numbers, you need to loop as many times as you want, while in method 2, you need to loop as many times as there are 1s.

class Solution:
    def hammingWeight(self, n: int) -> int:
        res = 0
        while n:
            res += 1  # 记录循环次数
            n &= n-1  # 逐渐将每个1变为0的关键步骤
        return res

In the key steps, it is understood in two steps.
The first step is to set n-1 first. What effect will n-1 have?
n-1 will reverse all the numbers starting from the rightmost 1 of n, and the left side of the rightmost 1 will remain unchanged. For example, 001100 is 001011 after subtracting 1.
In the second step, perform a bitwise AND operation on the result of n-1 and n. In the previous step, the rightmost 1 and the right 0 are reversed. Of course, the AND operation is 0, such as 001011 and 001100 obtained above. The AND operation is 00100, you see, is the rightmost 1 eliminated and turned into 0? Loop again until n becomes 000000.

Guess you like

Origin blog.csdn.net/weixin_45455015/article/details/118852982