开发者

Algorithm to count the number of 9s between 1000 and 2000 [closed]

开发者 https://www.devze.com 2023-03-03 14:44 出处:网络
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical andcannot be reasonably answered in its current form. For help clari
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. 开发者_如何学C Closed 11 years ago.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消