Count unset bits of a number | An optimized C # program to count unset bits in an integer . ; This makes sure two bits ( From MSB and including MSB ) are set ; This makes sure 4 bits ( From MSB and including MSB ) are set ; Count set bits in toggled number ; To store the count of set bits ; Driver code
using System ; class GFG { static int countUnsetBits ( int n ) { int x = n ; n |= n >> 1 ; n |= n >> 2 ; n |= n >> 4 ; n |= n >> 8 ; n |= n >> 16 ; return BitCount ( x ^ n ) ; } static int BitCount ( long x ) { int setBits = 0 ; while ( x != 0 ) { x = x & ( x - 1 ) ; setBits ++ ; } return setBits ; } public static void Main ( String [ ] args ) { int n = 17 ; Console . WriteLine ( countUnsetBits ( n ) ) ; } }