Please explain the logic behind Kernighan's bit counting algorithm

后端 未结 2 794
感情败类
感情败类 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:04

    Subtraction of 1 from a number toggles all the bits (from right to left) till the rightmost set bit(including the righmost set bit). So if we subtract a number by 1 and do bitwise & with itself (n & (n-1)), we unset the righmost set bit. In this way we can unset 1s one by one from right to left in loop.

    The number of times the loop iterates is equal to the number of set bits.

    Source : Brian Kernighan's Algorithm

提交回复
热议问题