Print first n numbers with exactly two set bits | Java program to print first n numbers with exactly two set bits ; Function to print first n numbers with two set bits ; Initialize higher of two sets bits ; Keep reducing n for every number with two set bits ; Consider all lower set bits for current higher set bit ; Print current number ; If we have found n numbers ; Consider next lower bit for current higher bit . ; Increment higher set bit ; Driver program
import java . io . * ; class GFG { static void printTwoSetBitNums ( int n ) { int x = 1 ; while ( n > 0 ) { int y = 0 ; while ( y < x ) { System . out . print ( ( ( 1 << x ) + ( 1 << y ) ) + " ▁ " ) ; n -- ; if ( n == 0 ) return ; y ++ ; } x ++ ; } } public static void main ( String [ ] args ) { int n = 4 ; printTwoSetBitNums ( n ) ; } }