Problem solving with programming: Counting the set bits in a number
Given an integer, how do we count the number of set (1) bits?
Method#2: Kernighan & Ritchie Method
it skips the zeroes wherever they appear.
This method is based on the observation that performing a bit-wise & operation between numand (num-1) clears the right most set bit.
For example If the given number is 129 ( 1000 0001). It unnecessarily goes though all the 0s between the first and last 1s.
Read full article from Problem solving with programming: Counting the set bits in a number
Given an integer, how do we count the number of set (1) bits?
Method#2: Kernighan & Ritchie Method
it skips the zeroes wherever they appear.
This method is based on the observation that performing a bit-wise & operation between numand (num-1) clears the right most set bit.
public static int getSetBitCount(int num) { int count = 0; while( num > 0) { num = num & (num-1); count++; } return count; }Method#1: Simple
public static int getSetBitCount(int num) { int count = 0; while( num > 0) { if( (num & 1) == 1) count++; num = num >> 1; } return count; }This method has a drawback that even if there less number of set bits, we have to go through all the bits to count the set bits.
For example If the given number is 129 ( 1000 0001). It unnecessarily goes though all the 0s between the first and last 1s.
Read full article from Problem solving with programming: Counting the set bits in a number