Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting digit occurrences

This problem is really confusing me; we're given two integers A, B, we want to count occurrences of digits in the range [A, B]. I though that if we could count the number of digit occurrences in the range [0, A] and [0, B], then the rest is trivial. So how can I count digit occurrences in a range [0, x]? This isn't homework, this is actually a problem from SPOJ. The naive approach won't work, as A and B can be as large as 10 ^ 9. Here are some examples:

Input:

1 10

Output:

1 2 1 1 1 1 1 1 1 1

Input:

44 497

Output:

85 185 185 185 190 96 96 96 95 93

like image 268
Chris Avatar asked Jan 19 '23 06:01

Chris


1 Answers

I would try the brute force approach first to get something working. Look at each number, iterate through each character in the string representation of that number, etc.

However, there is an easier way.

  • In the interval [0,9], 3 appears 1 time
  • In the interval [0,99], 3 appears 10 times in the first digit and 10 times in the second digit
  • In the interval [0,999], 3 appears 100 times in the first digit, 100 times in the second digit and 100 times in the third digit.

You can generalize this and with a bit of effort come up with a formula for how many of a certain digit (0 being a possible special case) will appear in a certain range. You don't need to actually go through each number.

like image 163
Mark Peters Avatar answered Feb 02 '23 15:02

Mark Peters