- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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 −
def solve(n, k): if k == 1: return(str(0)) else: arr =  arr2 =  while k > len(arr): templast = arr.copy() temp2last = arr2.copy() arr = templast +  + temp2last arr2 = templast +  + temp2last return(str(arr[k-1])) n = 4 k = 10 print(solve(n, k))
- Program to find the kth factor of n using Python
- Program to find kth smallest n length lexicographically smallest string in python
- Find the n-th binary string in sorted order in C++
- Find value of k-th bit in binary representation in C++
- Python program for removing n-th character from a string?
- Find k-th bit in a binary string created by repeated invert and append operations in C++
- N-th Fibonacci number in Python Program
- Program to find the kth smallest element in a Binary Search Tree in Python
- Program to find kth lexicographic sequence from 1 to n of size k Python
- Find i’th index character in a binary string obtained after n iterations in C++
- Python Program for n-th Fibonacci number
- C# program to remove n-th character from a string
- Find i’th Index character in a binary string obtained after n iterations in C++ programming
- Program to find maximum binary string after change in python
- 8085 program to find bit differences between two binary patterns.