Count unset bits of a number | JavaScript 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
function countUnsetBits ( n ) { let x = n ; n |= n >> 1 ; n |= n >> 2 ; n |= n >> 4 ; n |= n >> 8 ; n |= n >> 16 ; return BitCount ( x ^ n ) ; } function BitCount ( x ) { let setBits = 0 ; while ( x != 0 ) { x = x & ( x - 1 ) ; setBits ++ ; } return setBits ; } let n = 17 ; document . write ( countUnsetBits ( n ) ) ;