-
Notifications
You must be signed in to change notification settings - Fork 0
/
digit_sum.py
71 lines (52 loc) · 1.3 KB
/
digit_sum.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#Digit Sum
def contribute(number, digits,bound):
power = 10 ** digits
if bound == 0:
return power
if digits == 0:
return 1
return number % power + 1
def f(number, digits, bound, dp):
if digits == 0:
return 0
if dp[bound][digits] != -1:
return dp[bound][digits]
power = 10 ** (digits-1)
uperBound = 0
if bound == 1:
uperBound = number//power
else:
uperBound = 9
out = 0
i = 0
while i <= uperBound:
nextBound = 0
if bound == 1 and i == uperBound:
nextBound = 1
out += i * contribute(number,digits-1,nextBound)
out += f(number % power,digits -1,nextBound,dp)
i += 1
dp[bound][digits] = out
return out
def ilen(number):
out = 0
while number > 0:
number //=10
out += 1
return out
def main():
n = int(input())
for i in range(n):
lB,rB = input().split()
lB,rB = [int(lB), int(rB)]
rL = ilen(rB)
rdp = [[-1 for j in range(18)] for i in range(2)]
rSum = f(rB,rL,1,rdp)
if lB == 0:
print(rSum)
continue
lB -= 1
lL = ilen(lB)
ldp = [[-1 for j in range(18)] for i in range(2)]
print(rSum - f(lB,lL,1,ldp))
main()