Please explain the logic behind Kernighan's bit counting algorithm

后端 未结 2 796
感情败类
感情败类 2020-12-24 07:26

This question directly follows after reading through Bits counting algorithm (Brian Kernighan) in an integer time complexity . The Java code in question is

         


        
2条回答
  •  粉色の甜心
    2020-12-24 08:08

    Stepping through the code in a debugger helped me.

    If you start with

    n = 1010101 & n-1=1010100 => 1010100
    n = 1010100 & n-1=1010011 => 1010000
    n = 1010000 & n-1=1001111 => 1000000
    n = 1000000 & n-1=0111111 => 0000000
    

    So this iterates 4 times. Each iteration decrements the value in such a way that the least significant bit that is set to 1 disappears.

    Decrementing by one flips the lowest bit and every bit up to the first one. e.g. if you have 1000....0000 -1 = 0111....1111 not matter how many bits it has to flip and it stops there leaving any other bits set untouched. When you and this with n the lowest bit set and only the lowest bit becomes 0

提交回复
热议问题