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

Javascript
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.

Similar Reads

Approach 1: Using Recursive Function

Here, the recursive function generates all the binary strings of the input size ‘K’ without consecutive 1’s by actually appending the ‘0’ and the ‘1’ to the input string ‘str’. In each step there, is the appending of 0 or 1, and the binary strings are stored in the res variable and printed using the log function....

Approach 2: Using Stack Data Structure

In this specified approach, we are using the Stack Data Structure where the empty stack is used initially and pushed, and the popping of the binary strings is done to make sure that there are no consecutive 1s in the string. Then we display the results in the descending sequence....

Approach 3: Using Iteration and padStart() Method

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....

Approach 4: Using Backtracking

In this approach, we utilize backtracking to generate all binary strings of size K without consecutive 1’s. We start with an empty string and recursively explore all possible choices for each position in the string, ensuring that we append ‘0’ or ‘1’ only if it does not result in consecutive 1’s....