How to useIteration and padStart() Method in Javascript
In this approach, we are using the builtin methods to generate all the binary strings by performing the loop and mathematical operations. We convert the decimal number to a binary string and make sure that there are no consecutive 1s included in the string. Then we print these strings using the log function.
Example: In this example, we will Generate all binary strings without consecutive 1’s in JavaScript using Math.pow(), toString(), padStart() and includes() Methods
function binaryStr(K) {
let results = [];
for (let i = 0; i < Math.pow(2, K); i++) {
let res = i.toString(2).padStart(K, "0");
if (!res.includes("11")) {
results.push(res);
}
}
console.log(results.join(" "));
}
binaryStr(4);
Output
0000 0001 0010 0100 0101 1000 1001 1010
JavaScript Program to Generate all Binary Strings Without Consecutive 1’s
Given an integer, K. Generate all binary strings of size k without consecutive 1’s.
Examples:
Input : K = 3
Output : 000 , 001 , 010 , 100 , 101
Input : K = 4
Output: 0000 0001 0010 0100 0101 1000 1001 1010
Table of Content
- Approach 1: Using Recursive Function
- Approach 2: Using Stack Data Structure
- Approach 3: Using Iteration and padStart() Method
- Approach 4: Using Backtracking
So, let’s see each of the approaches with its practical implementation.