- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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
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
- Related Articles
- Program to find kth smallest n length lexicographically smallest string in python
- Program to find the kth factor of n using Python
- Find the n-th binary string in sorted order in C++
- Find value of k-th bit in binary representation in C++
- Program to find the kth smallest element in a Binary Search Tree in Python
- Find k-th bit in a binary string created by repeated invert and append operations in C++
- Python program for removing n-th character from a string?
- Program to find kth lexicographic sequence from 1 to n of size k Python
- N-th Fibonacci number in Python Program
- C# program to remove n-th character from a string
- Program to find maximum binary string after change in python
- Program to make a bulb switcher using binary string using Python
- Python Program for n-th Fibonacci number
- 8085 program to find bit differences between two binary patterns.
- Find n-th node in Postorder traversal of a Binary Tree in C++
