Print first n numbers with exactly two set bits | Prints 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 code
function printTwoSetBitNums ( n ) { let x = 1 ; while ( n > 0 ) { let y = 0 ; while ( y < x ) { document . write ( ( 1 << x ) + ( 1 << y ) + " " ) ; n -- ; if ( n == 0 ) return ; y ++ ; } x ++ ; } } printTwoSetBitNums ( 4 ) ;