Construct String of Alternating 1s and 0s 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: 2021-04-19T11:46:42+05:30

529 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements