Set all odd bits of a number | Return MSB set number ; Set all bits including MSB . ; Return MSB ; Returns a number of same size ( MSB at same position ) as n and all odd bits set . ; Generate odd bits like 010101. . ; If bits is even then shift by 1 ; Return odd set bits number ; Set all odd bits here ; Take OR with odd 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 ) == 0 ) n = n >> 1 ; return n ; } function setalloddbits ( n ) { return n | getevenbits ( n ) ; } let n = 10 ; document . write ( setalloddbits ( n ) ) ;