Highest power of 2 less than or equal to given number | Javascript program to find highest power of 2 smaller than or equal to n . ; check for the set bits ; Then we remove all but the top bit by xor ' ing ▁ the ▁ ▁ string ▁ of ▁ 1' s with that string of 1 ' s ▁ shifted ▁ one ▁ to ▁ ▁ the ▁ left , ▁ and ▁ we ▁ end ▁ up ▁ with ▁ just ▁ the ▁ one ▁ top ▁ bit ▁ ▁ followed ▁ by ▁ 0' s . ; Driver code
function highestPowerof2 ( x ) { x |= x >> 1 ; x |= x >> 2 ; x |= x >> 4 ; x |= x >> 8 ; x |= x >> 16 ; return x ^ ( x >> 1 ) ; } let n = 10 ; document . write ( highestPowerof2 ( n ) )