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
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
Steady State Response In this article, we are going to discuss the steady-state response. We will see what is steady state response in Time domain analysis. We will then discuss some of the standard test signals used in finding the response of a response. We also discuss the first-order response for different signals. We
9 min read
JavaScript Interview Questions and Answers JavaScript (JS) is the most popular lightweight, scripting, and interpreted programming language. JavaScript is well-known as a scripting language for web pages, mobile apps, web servers, and many other platforms. Both front-end and back-end developers need to have a strong command of JavaScript, as
15+ min read
React Tutorial React is a JavaScript Library known for front-end development (or user interface). It is popular due to its component-based architecture, Single Page Applications (SPAs), and Virtual DOM for building web applications that are fast, efficient, and scalable.Applications are built using reusable compon
8 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read