[Algorithm] Brian Kernigan algorithm-genius algorithm to find the number of 1 in binary

Topic background

When doing the Hamming distance of leetcode question 461, I found a very shameful algorithm for finding the number of 1, which is awesome!

Insert picture description here
In fact, the idea of ​​the subject itself is not difficult, it is to ask for the difference or and then count the number of 1, but I did not expect that it can be solved in this way.

Brian Knegan algorithm ideas

Is it possible to count the number of digits with 1 as a human intuitively, and skip the 0 between two 1s. For example: 10001000.

This is the basic idea of ​​Brian Kernigan's bit counting algorithm. This algorithm uses specific bits and arithmetic operations to remove the rightmost bit equal to 1.

When we do an AND bit operation on number and number-1, the rightmost bit of the original number number equal to 1 will be removed.

Based on the above ideas, the number of 1 in 1000 can be known through 2 iterations.

class Solution:
    def hammingDistance(self, x, y):
        xor = x ^ y
        distance = 0
        while xor:
            distance += 1
            # remove the rightmost bit of '1'
            xor = xor & (xor - 1)
        return distance

Ingenuity

Because after subtracting 1:

  1. The rightmost 1 must become 0
  2. All 0s on the right of the rightmost 1 must become 1.

Simultaneously:

  1. AND operation has no effect on the number on the left
  2. The AND operation erases the rightmost 1 0 each time

So as long as the result is not all 0 (conversely, as long as there are 1s), you can continue to perform the above minus 1 and AND operations. Each operation represents a 1, so the 1 is cleverly calculated Number

Finding a number based on the characteristics of binary arithmetic is really awkward. This requires a deep understanding of binary. . genius. .

Guess you like

Origin blog.csdn.net/weixin_38705903/article/details/109255076