Count unset bits of a number | An optimized Java 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 ; Driver code
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 Integer . bitCount ( x ^ n ) ; } public static void main ( String [ ] args ) { int n = 17 ; System . out . println ( countUnsetBits ( n ) ) ; } }