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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With