- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 −
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
- Related Articles
- Encoding a number string into a string of 0s and 1s in JavaScript
- Segregate all 0s on right and 1s on left in JavaScript
- Check if a string has m consecutive 1s or 0s in Python
- XOR counts of 0s and 1s in binary representation in C++
- Largest subarray with equal number of 0s and 1s in C++
- Print n 0s and m 1s such that no two 0s and no three 1s are together in C Program
- Python - List Initialization with alternate 0s and 1s
- Count Substrings with equal number of 0s, 1s and 2s in C++
- C Program to construct DFA accepting odd numbers of 0s and 1s
- Check if it is possible to rearrange a binary string with alternate 0s and 1s in Python
- Constructing a sentence based on array of words and punctuations using JavaScript
- Alternating sum of elements of a two-dimensional array using JavaScript
- Breaking a string into chunks of defined length and removing spaces using JavaScript
- Check if the binary representation of a number has equal number of 0s and 1s in blocks in Python
- Find the index of first 1 in an infinite sorted array of 0s and 1s in C++

Advertisements