text: Count set bits in an integer | C # program to count set bits by pre - storing count set bits in nibbles . ; Recursively get nibble of a given number and map them in the array ; Find last nibble ; Use pre - stored values to find count in last nibble plus recursively add remaining nibbles . ; Driver code
code: class GFG { static int [ ] num_to_bits = new int [ 16 ] { 0 , 1 , 1 , 2 , 1 , 2 , 2 , 3 , 1 , 2 , 2 , 3 , 2 , 3 , 3 , 4 } ; static int countSetBitsRec ( int num ) { int nibble = 0 ; if ( 0 == num ) return num_to_bits [ 0 ] ; nibble = num & 0xf ; return num_to_bits [ nibble ] + countSetBitsRec ( num >> 4 ) ; } static void Main ( ) { int num = 31 ; System . Console . WriteLine ( countSetBitsRec ( num ) ) ; } }