Problem:
I have seen questions like:
count the number of 0s between 0 and N?
count the number of 1s between 0 and N?
count the number of 2s between 0 and N?
- ... ...
These kinds of questions are very similar of asking to find the total number that Ks (i.e. K=0,1,2,...,9)
are shown in number range [0, N]
.
Example:
- Input:
K=2, N=35
- Output:
14
- Detail: list of
2
s between[0,35]
:2, 12, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 32
, note that22
will be counted as twice (as22
contains two2
s)
What we have:
There are solutions for each of them (available if you search for it). Usually, O(log N)
time is needed to solve such questions by recursively taking the highest digit into consideration, and so on. One example of counting the number of 2s between 0 and N can be solved by the following procedure (borrowed from here):
// Take n = 319 as example => 162
int numberOf2sBetween0AndN(int n)
{
if (n < 2)
return 0;
int result = 0;
int power10 = 1;
while (power10 * 10 < n)
power10 *= 10;
// power10 = 100
int msb = n / power10; // 3
int reminder = n % power10; // 19
/*** Count # of 2s from MSB ***/
if (msb > 2) // This counts the first 2 from 200 to 299
result += power10;
if (msb == 2) // If n = 219, this counts the first 2 from 200 to 219 (20 of 2s).
result += reminder + 1;
/*** Count # of 2s from reminder ***/
// This (recursively) counts for # of 2s from 1 to 100; msb = 3, so we need to multiply by that.
result += msb * numberOf2s(power10);
// This (recursively) counts for # of 2s from 1 to reminder
result += numberOf2s(reminder);
return result;
}
Question:
Note that, we cannot simply change all 2
s part in the above code to 1
s in order to solve the problem of counting the number of 1
s between 0
and N
. It seems that we have to handle differently (not trivial) for different cases.
Is there a general procedure we can follow to handle all K
s (i.e. K=0,1,2,...,9
), i.e. something like the following function?
int numberOfKsBetween0AndN(int k, int n)
Test cases:
Here are some test cases if you want to check your solution:
k=1, N=1
: 1k=1, N=5
: 1k=1, N=10
: 2k=1, N=55
: 16k=1, N=99
: 20k=1, N=10000
: 4001k=1, N=21345
: 18821k=2, N=10
: 1k=2, N=100
: 20k=2, N=1000
: 300k=2, N=2000
: 601k=2, N=2145
: 781k=2, N=3000
: 1900