Find N distinct numbers whose bitwise Or is equal to K | Java 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
import java . util . * ; class GFG { static final int MAX = 32 ; static long [ ] pow2 = new long [ MAX ] ; static boolean [ ] visited = new boolean [ MAX ] ; static Vector < Long > ans = new Vector < > ( ) ; static void power_2 ( ) { long ans = 1 ; for ( int i = 0 ; i < MAX ; i ++ ) { pow2 [ i ] = ans ; ans *= 2 ; } } static int countSetBits ( long x ) { int setBits = 0 ; while ( x != 0 ) { x = x & ( x - 1 ) ; setBits ++ ; } return setBits ; } static void add ( long num ) { int point = 0 ; long value = 0 ; for ( int i = 0 ; i < MAX ; i ++ ) { if ( visited [ i ] ) continue ; else { if ( num % 2 == 1 ) { value += ( 1 << i ) ; } num /= 2 ; } } ans . add ( value ) ; } static void solve ( long n , long k ) { ans . add ( k ) ; int countk = countSetBits ( k ) ; if ( pow2 [ countk ] < n ) { System . out . print ( - 1 ) ; return ; } int count = 0 ; for ( long i = 0 ; i < pow2 [ countk ] - 1 ; i ++ ) { add ( i ) ; count ++ ; if ( count == n ) break ; } for ( int i = 0 ; i < n ; i ++ ) { System . out . print ( ans . get ( i ) + " ▁ " ) ; } } public static void main ( String [ ] args ) { long n = 3 , k = 5 ; power_2 ( ) ; solve ( n , k ) ; } }