Find k-th bit in a binary string created by repeated invert and append operations
Last Updated :
27 Mar, 2023
You are given an initial string s starting with "0". The string keeps duplicating as follows. Invert of it is appended to it.
Examples:
Input : k = 2
Output : 1
Initially s = "0".
First Iteration : s = s + s' = "01"
Second Iteration : s = s + s' = "0110"
The digit at index 2 of s is 1.
Input : k = 12
Output : 0
1. Naive Approach
We can build the string s while its length is smaller than or equal to i in the manner mentioned in the problem description and then simply do a lookup of the required index in the string s.
C++
// C++ program to find k-th bit in a string
// formed by repeated invert and append
// operations.
#include <bits/stdc++.h>
using namespace std;
int printIndexVal(int k, string s)
{
while (s.length() <= k) {
// Building the complement of s
string t = "";
for (int i = 0; i < s.size(); i++) {
if (s[i] == '0')
t += '1';
else
t += '0';
}
// Appending the complement to form
// the new string
s += t;
}
// To match return type
return s[k] - '0';
}
// Driver program to test above function
int main()
{
string s = "0";
int k = 7;
cout << printIndexVal(k, s) << endl;
return 0;
}
Java
// Java program to find k-th bit in a string
// formed by repeated invert and append
// operations.
class GFG
{
static int printIndexVal(int k, String s)
{
while (s.length() <= k)
{
// Building the complement of s
String t = "";
for (int i = 0; i < s.length(); i++)
{
if (s.charAt(i) == '0')
t += '1';
else
t += '0';
}
// Appending the complement to form
// the new string
s += t;
}
// To match return type
return s.charAt(k) - '0';
}
// Driver code
public static void main(String[] args)
{
String s = "0";
int k = 7;
System.out.println(printIndexVal(k, s));
}
}
// This code is contributed by 29AjayKumar
Python3
# Python program to find k-th bit in a string
# formed by repeated invert and append
# operations.
def printIndexVal(k, s):
while (len(s) <= k):
# Building the complement of s
t = ""
for i in range(len(s)):
if (s[i] == '0'):
t += '1'
else:
t += '0'
# Appending the complement to form
# the new string
s += t
# To match return type
return ord(s[k]) - ord('0')
# Driver code
s = "0"
k = 7
print(printIndexVal(k, s))
# This code is contributed by shinjanpatra
C#
// C# program to find k-th bit in a string
// formed by repeated invert and append
// operations.
using System;
class GFG
{
static int printIndexVal(int k, String s)
{
while (s.Length <= k)
{
// Building the complement of s
String t = "";
for (int i = 0; i < s.Length; i++)
{
if (s[i] == '0')
t += '1';
else
t += '0';
}
// Appending the complement to form
// the new string
s += t;
}
// To match return type
return s[k] - '0';
}
// Driver code
public static void Main(String[] args)
{
String s = "0";
int k = 7;
Console.WriteLine(printIndexVal(k, s));
}
}
// This code contributed by Rajput-Ji
JavaScript
<script>
// JavaScript program to find k-th bit in a string
// formed by repeated invert and append
// operations.
function printIndexVal(k,s)
{
while (s.length <= k)
{
// Building the complement of s
let t = "";
for (let i = 0; i < s.length; i++)
{
if (s[i] == '0')
t += '1';
else
t += '0';
}
// Appending the complement to form
// the new string
s += t;
}
// To match return type
return s[k] - '0';
}
// Driver code
let s = "0";
let k = 7;
document.write(printIndexVal(k, s));
// This code is contributed by rag2127
</script>
Output:
1
Time Complexity: O(k log k).
Better Approach:
Let's take a look at a few string constructions:
1. s = 0
2. s = 01
3. s = 0110
4. s = 01101001
5. s = 0110100110010110
Let's consider finding the bit at position 11 in Line 5. The bit value at this position is effectively the complement of the bit at index 3 in Line 4. So we effectively need to find the complement of the bit at index 3.
s[11] = ~(s[3]). However we do not know s[3] either. Let's move ahead. Now s[3] = ~(s[1]) using the same explanation in Line 3. And s[1] = ~(s[0]). However, s[0] is always 0 from the problem statement.
Plugging these results,
s[11] = ~(~(~0)) = 1 where '~' is the bitwise NOT operator.
Now, k was initially 11 which is 1011 in binary. The next value of k was 3 that is 011. Notice how the first set bit has reduced from the original k. Subsequently, the next value of k is 1. Another set bit has reduced. Finally for k = 0, the last set bit has vanished. So for k = 11 which is 1011 in binary, the number of complements are 3, which is incidentally equal to the number of set bits in 11. Now we see for odd number of inversions the final result is 1. We can derive the same reasoning for even number of inversions yielding a final result as 0.
To count the number of set-bits in an integer, refer to this article - Count set bits in an integer.
CPP
// C++ program to find k-th bit in a string
// formed by repeated invert and append
// operations.
#include <bits/stdc++.h>
using namespace std;
int printIndexVal(int k)
{
// Variable to store set bits
unsigned long long int c = 0;
// Count set bits in a binary number
while (k > 0) {
k &= (k - 1);
c++;
}
// Return 1 if number of set bits
// is odd.
return c & 1;
}
// Driver Function
int main()
{
int k = 12;
cout << printIndexVal(k) << endl;
}
Java
// Java program to find k-th bit in a string
// formed by repeated invert and append
// operations.
import java.util.*;
class GFG {
public static int printIndexVal(int k) {
// Variable to store set bits
long c = 0;
// Count set bits in a binary number
while (k > 0) {
k &= (k - 1);
c++;
}
// Return 1 if number of set bits
// is odd.
return (int) (c & 1);
}
// Driver Function
public static void main(String[] args) {
int k = 12;
System.out.println(printIndexVal(k));
}
}
// This code is contributed by prince
Python3
# Python program to find k-th bit in a string
# formed by repeated invert and append
# operations.
import math
def printIndexVal(k):
# Variable to store set bits
c = 0
# Count set bits in a binary number
while k > 0:
k &= (k - 1)
c += 1
# Return 1 if number of set bits
# is odd.
return c & 1
# Driver Function
if __name__ == "__main__":
k = 12
print(printIndexVal(k))
# This code is contributed by adityashatmfh
JavaScript
// JavaScript program to find k-th bit in a string
// formed by repeated invert and append
// operations.
function printIndexVal(k)
{
// Variable to store set bits
let c = 0;
// Count set bits in a binary number
while (k > 0) {
k &= (k - 1);
c += 1;
}
// Return 1 if number of set bits
// is odd.
return c & 1;
}
// Driver Function
(function main() {
const k = 12;
console.log(printIndexVal(k));
})();
C#
using System;
public class Program {
// Function to find k-th bit in a string
// formed by repeated invert and append operations.
public static int PrintIndexVal(int k)
{
// Variable to store set bits
ulong c = 0;
// Count set bits in a binary number
while (k > 0) {
k &= (k - 1);
c++;
}
// Return 1 if number of set bits
// is odd, else return 0.
return (int)(c & 1);
}
// Driver Function
public static void Main()
{
int k = 12;
Console.WriteLine(PrintIndexVal(k));
}
}
// This code is contributed by sarojmcy2e
Output:
0
Time Complexity: O(log k)
References: https://www.hackerrank.com/contests/w32/challenges/duplication
Similar Reads
Mth bit in Nth binary string from a sequence generated by the given operations Given two integers N and M, generate a sequence of N binary strings by the following steps: S0 = "0"S1 = "1"Generate remaining strings by the equation Si = reverse(Si - 2) + reverse(Si - 1) The task is to find the Mth set bit in the Nth string. Examples: Input: N = 4, M = 3Output: 0Explanation:S0 ="
7 min read
Find i'th Index character in a binary string obtained after n iterations Given a decimal number m. Consider its binary representation string and apply n iterations. In each iteration, replace the character 0 with the string 01, and 1 with 10. Find the kth (1-based indexing) character in the string after the nth iterationExamples: Input: m = 5, n = 2, k = 5Output: 0Explan
15+ min read
Find iâth index character in a binary string obtained after n iterations | Set 2 Given a decimal number m, convert it into a binary string and apply n iterations, in each iteration 0 becomes â01â and 1 becomes â10â. Find ith(based indexing) index character in the string after nth iteration.Examples: Input: m = 5 i = 5 n = 3Output: 1ExplanationIn the first case m = 5, i = 5, n =
12 min read
Convert given Binary String to another in minimum operations by flipping all bits except any 1 Given two binary strings s1 and s2, the task is to count the minimum operations to convert string s1 to s2. In one operation a set bit can be chosen and all other bits except that is flipped. If it is not possible to convert s1-> s2 print -1. Examples: Input: s1 = "100010111" s2 = "101101100"Outp
12 min read
Position of leftmost set bit in given binary string where all 1s appear at end Given a binary string S of length N, such that all 1s appear on the right. The task is to return the index of the first set bit found from the left side else return -1. Examples: Input: s = 00011, N = 5Output: 3Explanation: The first set bit from the left side is at index 3. Input: s = 0000, N = 4Ou
5 min read