Set all even bits of a number | Return msb set number ; Set all bits ; Return msb increment n by 1 and shift by 1 ; Return even seted number ; Get msb here ; Generate even bits like 101010. . ; If bits is odd then shift by 1 ; Return even set bits number ; Set all even bits here ; Take or with even set bits number ; Driver code
function getmsb ( n ) { n |= n >> 1 ; n |= n >> 2 ; n |= n >> 4 ; n |= n >> 8 ; n |= n >> 16 ; return ( n + 1 ) >> 1 ; } function getevenbits ( n ) { n = getmsb ( n ) ; n |= n >> 2 ; n |= n >> 4 ; n |= n >> 8 ; n |= n >> 16 ; if ( ( n & 1 ) == 1 ) n = n >> 1 ; return n ; } function setallevenbits ( n ) { return n | getevenbits ( n ) ; } let n = 10 ; document . write ( setallevenbits ( n ) ) ;