Set all even bits of a number | Efficient Java program to 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
import java . io . * ; class GFG { static int getmsb ( int n ) { n |= n >> 1 ; n |= n >> 2 ; n |= n >> 4 ; n |= n >> 8 ; n |= n >> 16 ; return ( n + 1 ) >> 1 ; } static int getevenbits ( int 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 ; } static int setallevenbits ( int n ) { return n | getevenbits ( n ) ; } public static void main ( String [ ] args ) { int n = 10 ; System . out . println ( setallevenbits ( n ) ) ; } }