Algorithm to count the number of 9s between 1000 and 2000 [closed]
Can anyone please let me the efficient algorithm to count the number of 9s present between 1000 and 2000.
Since it's a fixed number you could precalculate it and hard code it.
There should be 300 nines in that interval.
There is 100*1 nines as the first digit (1009, 1019, ...)
There is 10*10 nines as second digit (1090, 1091, ..., 1190, 1191, ...)
There is 1*100 nines as third digit (1900, 1901, ...)
I can add that 1999 counts as 3 nines for me.
A simple way to do this in JavaScript (since you didn't mention a language) would be
var x = 0,
i = 1000;
for (; i < 2000; i++) if (/9/.test(i.toString()))
x++;
When the loop finishes, x would be the amount of numbers between 1000 and 2000 with the number 9 in them.
精彩评论