Program to find Kth bit in n-th binary string using Python


Suppose we have two positive values n and k, now we can make a binary string S_n by using following rules −

  • S_1 = 0

  • S_i = S_i-1 concatenate "1" concatenate reverse(invert(S_i-1)) for i > 1

Here reverse(x) returns the reversed string x, and invert(x) flips all the bits in x.

These are the example of four such strings

  • S_1 = "0"

  • S_2 = "011"

  • S_3 = "0111001"

  • S_4 = "011100110110001"

We have to find kth bit in S_n.

So, if the input is like n = 4 k = 10, then the output will be 1 because S_4 = "011100110110001", so 10th bit is 1 (first bit is at position 1).

To solve this, we will follow these steps −

  • if k is same as 1, then

    • return 0 as string

  • otherwise,

    • arr := an array with single element 0

    • arr2 := an array with single element 1

    • while k > size of arr, do

      • templast := copy of arr

      • temp2last := copy of arr2

      • arr := templast concatenate 1 concatenate temp2last

      • arr2 := templast concatenate 0 concatenate temp2last

  • return k-1 th element from arr

Let us see the following implementation to get better understanding −

Example

def solve(n, k):
   if k == 1:
      return(str(0))
   else:
      arr = [0]
      arr2 = [1]
      while k > len(arr):
         templast = arr.copy()
         temp2last = arr2.copy()
         arr = templast + [1] + temp2last
         arr2 = templast + [0] + temp2last
      return(str(arr[k-1]))
n = 4
k = 10
print(solve(n, k))

Input

4, 10

Output

1

Updated on: 29-May-2021

244 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements