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
Counting the number of 1s upto n in JavaScript
Counting the number of 1s from 1 to n is a common algorithmic problem in JavaScript. We need to count how many times the digit "1" appears in all positive integers up to and including n.
For example, if n = 31, the digit "1" appears in: 1, 10, 11 (twice), 12, 13, 14, 15, 16, 17, 18, 19, 21, 31. That's a total of 14 occurrences.
Problem Analysis
The challenge is to efficiently count digit occurrences without iterating through every number. We can solve this using digit-by-digit analysis or a simpler brute force approach.
Method 1: Brute Force Approach
The simplest method converts each number to a string and counts occurrences of "1":
function countOnesSimple(n) {
let count = 0;
for (let i = 1; i <= n; i++) {
let str = i.toString();
for (let char of str) {
if (char === '1') {
count++;
}
}
}
return count;
}
// Test with example
const num = 31;
console.log(`Count of 1s up to ${num}:`, countOnesSimple(num));
// Additional test cases
console.log("Count up to 13:", countOnesSimple(13));
console.log("Count up to 100:", countOnesSimple(100));
Count of 1s up to 31: 14 Count up to 13: 6 Count up to 100: 21
Method 2: Optimized Mathematical Approach
For better performance with large numbers, we can use a mathematical approach that analyzes each digit position:
function countOnesOptimized(n) {
if (n <= 0) return 0;
let count = 0;
let factor = 1;
while (factor <= n) {
let higher = Math.floor(n / (factor * 10));
let current = Math.floor(n / factor) % 10;
let lower = n % factor;
if (current === 0) {
count += higher * factor;
} else if (current === 1) {
count += higher * factor + lower + 1;
} else {
count += (higher + 1) * factor;
}
factor *= 10;
}
return count;
}
// Test the optimized approach
console.log("Optimized count up to 31:", countOnesOptimized(31));
console.log("Optimized count up to 1000:", countOnesOptimized(1000));
Optimized count up to 31: 14 Optimized count up to 1000: 301
How the Mathematical Approach Works
The algorithm examines each digit position and calculates how many 1s appear in that position across all numbers from 1 to n. It considers three cases based on the current digit:
- Current digit = 0: Count = higher × factor
- Current digit = 1: Count = higher × factor + lower + 1
- Current digit > 1: Count = (higher + 1) × factor
Performance Comparison
| Method | Time Complexity | Best For |
|---|---|---|
| Brute Force | O(n × log n) | Small numbers, easier to understand |
| Mathematical | O(log n) | Large numbers, optimal performance |
Complete Example with Validation
function countOnes(n) {
// Input validation
if (!Number.isInteger(n) || n <= 0) {
return 0;
}
let count = 0;
let factor = 1;
while (factor <= n) {
let higher = Math.floor(n / (factor * 10));
let current = Math.floor(n / factor) % 10;
let lower = n % factor;
if (current === 0) {
count += higher * factor;
} else if (current === 1) {
count += higher * factor + lower + 1;
} else {
count += (higher + 1) * factor;
}
factor *= 10;
}
return count;
}
// Test various cases
const testCases = [31, 13, 100, 111, 1234];
testCases.forEach(num => {
console.log(`Count of 1s up to ${num}: ${countOnes(num)}`);
});
Count of 1s up to 31: 14 Count of 1s up to 13: 6 Count of 1s up to 100: 21 Count of 1s up to 111: 36 Count of 1s up to 1234: 689
Conclusion
Both approaches solve the problem effectively. Use the brute force method for simplicity and small inputs, or the mathematical approach for optimal performance with large numbers. The mathematical solution provides O(log n) time complexity, making it suitable for competitive programming scenarios.
