Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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));
101010101010
Alternative Methods
Using String Repetition and Slice
For better performance with larger strings, we can create the pattern once and repeat it:
const buildStringFast = (num) => {
const pattern = '10';
return pattern.repeat(Math.ceil(num / 2)).slice(0, num);
};
console.log(buildStringFast(8)); // Length 8
console.log(buildStringFast(15)); // Length 15
10101010 101010101010101
Using Ternary Operator
A more concise version using the ternary operator:
const buildStringTernary = (num) => {
let result = '';
for(let i = 0; i < num; i++){
result += i % 2 === 0 ? '1' : '0';
}
return result;
};
console.log(buildStringTernary(10));
console.log(buildStringTernary(7));
1010101010 1010101
Performance Comparison
| Method | Time Complexity | Best For |
|---|---|---|
| Loop with concatenation | O(n) | Small to medium strings |
| String repeat and slice | O(n) | Large strings, better performance |
| Ternary operator | O(n) | Code readability |
Edge Cases
// Handle edge cases console.log(buildString(0)); // Empty string console.log(buildString(1)); // Single character console.log(buildString(2)); // Two characters
1 10
Conclusion
All three methods effectively create alternating strings of 1s and 0s. The string repeat method offers better performance for large strings, while the loop approach is more straightforward and easier to understand.
Advertisements
