Highest power of 2 less than or equal to given number | Java 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
import java . io . * ; class GFG { static int highestPowerof2 ( int x ) { x |= x >> 1 ; x |= x >> 2 ; x |= x >> 4 ; x |= x >> 8 ; x |= x >> 16 ; return x ^ ( x >> 1 ) ; } public static void main ( String [ ] args ) { int n = 10 ; System . out . println ( highestPowerof2 ( n ) ) ; } }