JavaScript Program to Find i’th Index Character in a Binary String Obtained After n Iterations
Last Updated :
16 Jul, 2024
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 the (based on indexing) index character in the string after the nth iteration.
Input: m = 5, n = 2, i = 3
Output: 1
Input: m = 3, n = 3, i = 6
Output: 1
Approach 1
- Convert a decimal number into its binary representation and store it as a string 's'.
- Iterate 'n' times, and in each iteration, replace '0' with "01" and '1' with "10" in the string 's' by running another loop over its length, storing the modified string in 's1' after each iteration.
- After all, iterations, return the character at the 'ith' index in the final string 's'.
JavaScript
// Javascript Program to find ith
// character in a binary String.
let s = "";
// Function to store binary Representation
function binary_conversion(m) {
while (m !== 0) {
let tmp = m % 2;
s += tmp.toString();
m = Math.floor(m / 2);
}
s = s.split("").reverse().join("");
}
// Function to find ith character
function find_character(n, m, i) {
// Function to change decimal to binary
binary_conversion(m);
let s1 = "";
for (let x = 0; x < n; x++) {
let temp = "";
for (let y = 0; y < s.length; y++) {
temp += s[y] === '1' ? "10" : "01";
}
// Assign temp String in s String
s = temp;
}
return s[i] === '1' ? 1 : 0;
}
let m = 5, n = 2, i = 8;
console.log(find_character(n, m, i));
Time Complexity: O(N)
Space Complexity: O(N), where N is the length of string.
Approach 2
- In this approach, we calculate the ith character in a binary string after n iterations.
- It converts a decimal number M into its binary representation, finds the block number where the character is, and handles special cases when k corresponds to the root digit.
- We use bitwise operations to efficiently determine whether to flip the root digit or not.
- The result is then printed, providing the desired character within the modified binary string.
JavaScript
// Javascript program to find ith
// Index character in a binary
// string obtained after n iterations
// Function to find
// the i-th character
function KthCharacter(m, n, k) {
// Distance between two
// consecutive elements
// after N iterations
let distance = Math.pow(2, n);
let Block_number = Math.floor(k / distance);
let remaining = k % distance;
let s = new Array(32).fill(0);
let x = 0;
// Binary representation of M using a while loop
while (m > 0) {
s[x] = m % 2;
m = Math.floor(m / 2);
x++;
}
// kth digit will be
// derived from root
// for sure
let root = s[x - 1 -
Block_number];
if (remaining == 0) {
console.log(root);
return;
}
// Check whether there is
// need to flip root or not
let flip = true;
while (remaining > 1) {
if ((remaining & 1) > 0) {
flip = !flip;
}
remaining = remaining >> 1;
}
if (flip) {
console.log((root > 0) ? 0 : 1);
}
else {
console.log(root);
}
}
let m = 5, k = 5, n = 3;
KthCharacter(m, n, k);
Time Complexity: O(log N)
Space Complexity: O(1)
Approach 3
Mathematical Approach:
This approach leverages the recursive nature of the transformation and the properties of binary strings to directly compute the
? ith character. It recursively determines whether the ? ith character will be 0 or 1 based on the initial binary representation and the transformations applied.
Detailed Steps:
1. Binary Conversion: Convert the given decimal number ? m to its binary representation.
2. Recursive Calculation: For each bit, determine its value after ? n transformations using a recursive approach.
Example:
JavaScript
function getIthCharacter(m, n, i) {
// Function to convert decimal to binary and store as a string
function toBinaryString(m) {
return m.toString(2);
}
// Recursive function to find the ith character after n iterations
function findIthChar(binaryStr, n, i) {
if (n == 0) {
// Base case: if no iterations left, return the character at position i
return binaryStr[i];
}
let length = Math.pow(2, n); // Length of the string after n iterations
let mid = length / 2;
if (i < mid) {
// If i is in the first half, it corresponds to the same position in the previous iteration
return findIthChar(binaryStr, n - 1, i);
} else {
// If i is in the second half, it corresponds to the complement of the position in the first half
return findIthChar(binaryStr, n - 1, i - mid) == '0' ? '1' : '0';
}
}
let binaryStr = toBinaryString(m); // Convert m to binary
return findIthChar(binaryStr, n, i);
}
// Example usage:
let m = 5, n = 2, i = 3;
console.log(getIthCharacter(m, n, i)); // Output: 1
m = 3, n = 3, i = 6;
console.log(getIthCharacter(m, n, i)); // Output: 1
Approach 4: Iterative Direct Calculation
In this approach, instead of generating the entire string after each iteration, we directly compute the value of the character at the i-th position by understanding the pattern of transformations. This approach leverages the direct calculation of index transformations without needing to explicitly construct the entire binary string at each step.
Detailed Steps:
- Binary Conversion: Convert the given decimal number m to its binary representation.
- Iterative Transformation: Calculate the position and value of the i-th character by iteratively understanding the pattern of changes at each iteration.
Example:
JavaScript
function getIthCharacter(m, n, i) {
function toBinaryString(m) {
return m.toString(2);
}
function findIthChar(binaryStr, n, i) {
while (n > 0) {
let length = Math.pow(2, n);
let mid = length / 2;
if (i < mid) {
} else {
i -= mid;
binaryStr = binaryStr.split('').map(char => char === '0' ? '1' : '0').join(''); // Complement the binary string
}
n--;
}
return binaryStr[i];
}
let binaryStr = toBinaryString(m);
return findIthChar(binaryStr, n, i);
}
let m = 5, n = 2, i = 3;
console.log(getIthCharacter(m, n, i))
m = 3, n = 3, i = 6;
console.log(getIthCharacter(m, n, i))
Similar Reads
JavaScript Program to FindNumber of Flips to make Binary String Alternate In this problem, we aim to determine the minimum number of flips needed to transform a binary string into an alternating sequence of '0's and '1's. A flip refers to changing a '0' to '1' or a '1' to '0'. The objective is to find the most efficient way to achieve this alternating pattern.Examples:Inp
4 min read
JavaScript Program to Generate all Binary Strings From Given Pattern In this article, we are going to learn about Generating all binary strings from a given pattern in JavaScript. Generating all binary strings from a given pattern involves creating a set of binary sequences that follow the pattern's structure, where specific positions in the sequences can be filled w
3 min read
JavaScript Program to Count Strings with Consecutive 1âs Given a number n, count the Optimized number of n-length strings with consecutive 1s in them.Examples:Input : n = 2Output : 1There are 4 strings of length 2, thestrings are 00, 01, 10 and 11. Only the string 11 has consecutive 1's.Input : n = 3Output : 3There are 8 strings of length 3, thestrings ar
7 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
Java Program to Convert Octal to Binary Given an Octal number as input, the task is to convert that number into its Binary equivalent number. Example: Input: Octal Number = 513 Output: Binary equivalent value is: 101001011 Explanation : Binary equivalent value of 5: 101 Binary equivalent value of 1: 001 Binary equivalent value of 3: 011Oc
5 min read
Reverse the string whenever digit is encountered Given a string s of length N, the task is to traverse the string and reverse the substring from the start to the next encountered digit. After reversing the substring, update the start index to the character immediately following the digit. Example: Input: s = abc123def456ghiOutput: cba123fed456ihg
4 min read
Find i'th Index character in a binary string obtained after n iterations 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 the (based on indexing) index character in the string after the nth iteration. Examples: Input : m = 5, n = 2, i = 3Output : 1Input : m = 3, n = 3, i = 6Output
6 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
Find k-th bit in a binary string created by repeated invert and append operations 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
8 min read
Convert String into Binary Sequence Given a string of character the task is to convert each character of a string into the equivalent binary number. Examples : Input : GFG Output : 1000111 1000110 1000111 Input : geeks Output : 1100111 1100101 1100101 1101011 1110011 The idea is to first calculate the length of the string as n and the
5 min read