Find N distinct numbers whose bitwise Or is equal to K in Python


Suppose we have two integers N and K; we have to find N unique values whose bit-wise OR is same as K. If there is no such result, then return -1

So, if the input is like N = 4 and K = 6, then the output will be [6,0,1,2].

To solve this, we will follow these steps −

  • MAX := 32

  • visited := a list of size MAX and fill with False

  • res := a new list

  • Define a function add() . This will take num

  • point := 0

  • value := 0

  • for i in range 0 to MAX, do

    • if visited[i] is non-zero, then

      • go for next iteration

    • otherwise,

      • if num AND 1 is non-zero, then

        • value := value +(2^i)

      • num := num/2 (take only integer part)

  • insert value at the end of res

  • From the main method, do the following −

  • pow2 := an array of power of 2 from 2^0 to 2^31

  • insert k at the end of res

  • cnt_k := number of bits in k

  • if pow2[cnt_k] < n, then

    • return -1

  • count := 0

  • for i in range 0 to pow2[cnt_k] - 1, do

    • add(i)

    • count := count + 1

    • if count is same as n, then

      • come out from the loop

  • return res

Example

Let us see the following implementation to get better understanding −

 Live Demo

MAX = 32
visited = [False for i in range(MAX)]
res = []
def set_bit_count(n):
   if (n == 0):
      return 0
   else:
      return (n & 1) + set_bit_count(n >> 1)
def add(num):
   point = 0
   value = 0
   for i in range(MAX):
      if (visited[i]):
         continue
      else:
         if (num & 1):
            value += (1 << i)
         num = num//2
   res.append(value)
def solve(n, k):
   pow2 = [2**i for i in range(MAX)]
   res.append(k)
   cnt_k = set_bit_count(k)
   if (pow2[cnt_k] < n):
      return -1
   count = 0
   for i in range(pow2[cnt_k] - 1):
      add(i)
      count += 1
      if (count == n):
         break
   return res

n = 4
k = 6
print(solve(n, k))

Input

4, 6

Output

[6, 0, 1, 2]

Updated on: 25-Aug-2020

78 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements