(1)讲的明白,但写的明白吗? - SegmentFault
一本书的页码从自然数1开始编码直到自然数n,按照通常的习惯,每个页码都不包含多余的前导数字0,例如第6页用数字6而不是06或者006表示。现在给定表示书的总页码的十进制整数n(1 =< n <= 10^9),编程计算书的全部页码中分别用到多少次数字0, 1, 2, 3, 4, 5, 6, 7, 8, 9。
def count_num(num):
nums = [0 for x in range(10)]
if num < 10:
for i in range(1, num + 1):
nums[i] = 1
return nums
# Part 1
for i in range(1, 10):
nums[i] += 1
# Part 2
units = num % 10
for i in range(0, units + 1):
nums[i] += 1
# Part 3
others = num / 10 - 1
for i in range(0, 10):
nums[i] += others
# Part4
count_others = count_num(others)
for i in range(10):
times_i = count_others[i] * 10
nums[i] += times_i
# Part 5
digit_keep = []
while num > 0:
digit_keep.append(num % 10)
num = num / 10
times_units = digit_keep[0] + 1
for digit in digit_keep[1:]:
nums[digit] += times_units
return nums
Read full article from (1)讲的明白,但写的明白吗? - SegmentFault