Count integer occurrence within number range
The digit "1" appears twice between 0 and 10.
Sometimes in life, you need to find out weird facts, such as how many times the digit 1 occurs in a number range sequence of 0 to 10 (the answer is 2 times, appearing as "1" and the "1" in "10"). This came up a couple of years ago in a Reddit discussion thread that I was involved in (will post the link if I can find it).
Once again, JavaScript is a very lightweight tool that we can use to perform calculation.
The logic behind the looniness
Goal: Find out how many times the number 1 occurs in a number sequence range of 0 to 10.
We have 3 variables in this calculation:
a
: This is the starting number of the range e.g. 0.b
: This is the ending number of the range e.g. 10.c
: This is the number to find within the range e.g. 1.
The JavaScript to do the work for us is only 5 lines long!
var result = 0;
for (var i = startNumberA; i <= endNumberB; i++) {
result += (i.toString().match(new RegExp(numToFindC.toString(), "g")) || []).length;
}
return result;
We are using a simple loop and counting from the start of the range e.g. 0, right through to the final number in the range e.g. 10 (inclusive).
For each number in the range, a Regular Expression match is run, which in simple terms, counts how many times the search c
variable occurs between a
and b
, and then adds that quantity to the existing counter.
Calculation result
Using the above counter, we can accurately determine, that the number 1 appears twice between and including 0 and 10:
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 = 2
Our answer is 2.
Working Result from JSFiddle
Jump straight to the Result tab to see the calculator.
You might also be interested in these articles...
Optimising the small things in life, for developers and people.