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: I
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 for Min flips of continuous characters to make all characters same in a String
In this article, we will learn about Min flips of continuous characters to make all characters the same in a string using JavaScript. Min flips of continuous characters in a string refer to the minimum number of changes required to turn a sequence of adjacent characters into a uniform sequence, ensu
3 min read
JavaScript Program to find the Index of Last Occurrence of Target Element in Sorted Array
In this article, we will see the JavaScript program to get the last occurrence of a number in a sorted array. We have the following methods to get the last occurrence of a given number in the sorted array. Methods to Find the Index of the Last Occurrence of the Target Element in the Sorted ArrayUsin
4 min read
JavaScript Program to Find First Set Bit
The rightmost bit in a binary representation of a number that is set to 1 is called the "First Set Bit". It indicates the lowest significant bit where the value changes from 0 to 1. Examples: Input: N = 18Output: 2Explanation: Binary representation of 18 is 010010,the first set bit from the right si
3 min read
JavaScript Program to Find the First Repeated Word in String
Given a string, our task is to find the 1st repeated word in a string. Examples: Input: âRavi had been saying that he had been thereâOutput: hadInput: âRavi had been saying thatâOutput: No RepetitionBelow are the approaches to Finding the first repeated word in a string: Table of Content Using SetUs
4 min read
JavaScript Program to Find the Position of the Rightmost Set Bit
Given a number, the task is to find the position of the rightmost set bit. The indexing is from right to left, where the rightmost bit position starts from 1. Example: Input: n = 20Output: 3Explanation: Binary Representation of 20 is 10100, hence position of first set bit from right is 3.Input: n =
3 min read
JavaScript Program to find Lexicographically next String
In this article, we are going to learn how can we find the Lexicographically next string. Lexicographically next string refers to finding the string that follows a given string in a dictionary or alphabetical order. Examples: Input : testOutput : tesuExplanation : The last character 't' is changed t
3 min read
JavaScript Program to Print the First Letter of Each Word
Printing the first letter of each word involves extracting the initial character from every word in a given string, typically accomplished by splitting the string into words and selecting the first character from each resulting word. Examples of Printing the First Letter of Each Word Table of Conten
3 min read
JavaScript Program for Binary Representation of Next Number
Given a binary input that represents a binary representation of the positive number n, find a binary representation of n+1. We will try to find out this with the different approaches discussed below. Examples: Input : 10011 Output : 10100 Here n = (19)10 = (10011)2 next greater integer = (20)10 = (1
3 min read