3.Number of 1 Bits
Solution I: (Using STL)
Solution II: (Brian Kernighan’s Algorithm)
Algorithm:
Subtracting 1 from a decimal number flips all the bits after the rightmost set bit(which is 1) including the rightmost set bit.
For example for 4 ( 100) and 16(10000), we get the following after subtracting 3 –> (011 ) , 15 –> (01111)
It integer is not 0 * Do bitwise & with (n-1) and assign the value to n * increment the count by 1.
Time Complexity: O(log n)
Last updated