Đếm chữ số trong đoạn từ [1,n]
import math
A = [1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000]
def pro(num, len, count):
n = num // A[len]
if num == 0:
count[n] += len + 1
return
for i in range(n):
count[i] += A[len]
count[n] += num % A[len] + 1
if len == 0:
return
for i in range(10):
count[i] += n * len * A[len - 1]
pro(num % A[len], len - 1, count)
def main():
while True:
try:
a, b = map(int, input().split())
if a + b == 0:
break
except ValueError:
break
if a > b:
a, b = b, a
a -= 1
count1 = [0] * 10
count2 = [0] * 10
if a:
p1 = int(math.floor(math.log10(a)))
pro(a, p1, count1)
for i in range(p1 + 1):
count1[0] -= A[i]
p2 = int(math.floor(math.log10(b)))
pro(b, p2, count2)
for i in range(p2 + 1):
count2[0] -= A[i]
print(count2[0] - count1[0], end='')
for i in range(1, 10):
print(f" {count2[i] - count1[i]}", end='')
print()
if __name__ == "__main__":
main()
Bình luận (1)