JavaScript: Count total number of 1s from 1 to N
JavaScript Math: Exercise-102 with Solution
Count Digit 1 in Range
Write a JavaScript program to count the number of times the digit 1 appears in 1 to a given number.
Example : 11, 1 appears 4 time between 1 to 11 [1->1, 10->1 ,11-.2]
Test Data:
(11) -> 4
(305) -> 161
(0) -> false
Sample Solution:
Solution-1
JavaScript Code:
Output:
n = 11 Total number of 1s from 1 to n: 4 n = 305 Total number of 1s from 1 to n: 161 n = 0 Total number of 1s from 1 to n: false
Flowchart:

Live Demo:
Solution-2
JavaScript Code:
Output:
n = 11 Total number of 1s from 1 to n: 4 n = 305 Total number of 1s from 1 to n: 161 n = 0 Total number of 1s from 1 to n: false
Flowchart:

Live Demo:
For more Practice: Solve these Related Problems:
- Write a JavaScript function that counts the number of times the digit '1' appears in all numbers from 1 to a given number using string conversion.
- Write a JavaScript function that iterates over each number in the range and counts the occurrences of '1' in its decimal representation.
- Write a JavaScript function that optimizes the count by analyzing each digit position across the range.
- Write a JavaScript function that validates the input and returns an error for non-positive numbers before counting.
Improve this sample solution and post your code through Disqus.
Previous: Find the nth ugly number.
Next: Product of two non-negative integers as strings.
What is the difficulty level of this exercise?
Based on 2312 votes, average difficulty level of this exercise is Hard
.
Test your Programming skills with w3resource's quiz.