Find N distinct numbers whose bitwise Or is equal to K | Javascript implementation of the approach ; Function to pre - calculate all the powers of 2 upto MAX ; Function to return the count of set bits in x ; To store the count of set bits ; Function to add num to the answer by setting all bit positions as 0 which are also 0 in K ; Bit i is 0 in K ; Function to find and print N distinct numbers whose bitwise OR is K ; Choosing K itself as one number ; Find the count of set bits in K ; Impossible to get N distinct integers ; Add i to the answer after setting all the bits as 0 which are 0 in K ; If N distinct numbers are generated ; Print the generated numbers ; Driver code ; Pre - calculate all the powers of 2
const MAX = 32 ; let pow2 = new Array ( MAX ) ; let visited = new Array ( MAX ) ; let ans = [ ] ; function power_2 ( ) { let ans = 1 ; for ( let i = 0 ; i < MAX ; i ++ ) { pow2 [ i ] = ans ; ans *= 2 ; } } function countSetBits ( x ) { let setBits = 0 ; while ( x != 0 ) { x = x & ( x - 1 ) ; setBits ++ ; } return setBits ; } function add ( num ) { let point = 0 ; let value = 0 ; for ( let i = 0 ; i < MAX ; i ++ ) { if ( visited [ i ] ) continue ; else { if ( num & 1 ) { value += ( 1 << i ) ; } num = parseInt ( num / 2 ) ; } } ans . push ( value ) ; } function solve ( n , k ) { ans . push ( k ) ; let countk = countSetBits ( k ) ; if ( pow2 [ countk ] < n ) { document . write ( - 1 ) ; return ; } let count = 0 ; for ( let i = 0 ; i < pow2 [ countk ] - 1 ; i ++ ) { add ( i ) ; count ++ ; if ( count == n ) break ; } for ( let i = 0 ; i < n ; i ++ ) { document . write ( ans [ i ] + " " ) ; } } let n = 3 , k = 5 ; power_2 ( ) ; solve ( n , k ) ;