Constructing a string of alternating 1s and 0s of desired length using JavaScript


Problem

We are required to write a JavaScript function that takes in a number n. Starting with ‘1’ our function should construct a string of length n that contains ‘1’ and ‘0’ alternatingly.

Example

Following is the code −

 Live Demo

const num = 12;
const buildString = (num = 1) => {
   let res = '';
   for(let i = 0; i < num; i++){
      if(i % 2 === 0){
         res += 1;
      }else{
         res += 0;
      };
   };
   return res;
};
console.log(buildString(num));

Output

101010101010

Updated on: 19-Apr-2021

447 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements