Updated Answer
My original answer was simple to understand but tricky to code. Here's something that is simpler to code. It's a straight-forward non-recursive solution that works by counting the number of ways zeros can appear in each position.
For example:
x <= 1234. How many numbers are there of the following form?
x = ??0?
There are 12 possibilities for the "hundreds or more" (1,2, ..., 12). Then there must be a zero. Then there are 10 possibilities for the last digit. This gives 12 * 10 = 120
numbers containing a 0 at the third digit.
The solution for the range (1 to 1234) is therefore:
- ?0??: 1 * 100 = 100
- ??0?: 12 * 10 = 120
- ???0: 123
- Total = 343
But an exception is if n
contains a zero digit. Consider the following case:
x <= 12034. How many numbers are there of the following form?
x = ??0??
We have 12 ways to pick the "thousands or more". For 1, 2, ... 11 we can choose any two last digits (giving 11 * 100 possibilities). But if we start with 12 we can only choose a number between 00
and 34
for the last two digits. So we get 11 * 100 + 35
possibilities altogether.
Here's an implementation of this algorithm (written in Python, but in a way that should be easy to port to C):
def countZeros(n):
result = 0
i = 1
while True:
b, c = divmod(n, i)
a, b = divmod(b, 10)
if a == 0:
return result
if b == 0:
result += (a - 1) * i + c + 1
else:
result += a * i
i *= 10
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…