-
Notifications
You must be signed in to change notification settings - Fork 5
/
solution.py
77 lines (62 loc) · 1.64 KB
/
solution.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
72
73
74
75
76
77
from typing import Optional
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
dummy = ListNode(0)
cur = dummy
sum = 0
while l1 or l2 or sum:
if l1:
sum += l1.val
l1 = l1.next
if l2:
sum += l2.val
l2 = l2.next
cur.next = ListNode(sum % 10)
cur = cur.next
sum //= 10
return dummy.next
class Example:
def __init__(self, l1, l2, ans):
self.l1 = l1
self.l2 = l2
self.ans = ans
def buildList(nums):
dummy = ListNode(0)
cur = dummy
for num in nums:
cur.next = ListNode(num)
cur = cur.next
return dummy.next
def check(l1, l2):
p, q = l1, l2
while p and q and p.val == q.val:
p = p.next
q = q.next
return p == q
def main():
examples = [Example(
buildList([2, 4, 3]),
buildList([5, 6, 4]),
buildList([7, 0, 8])
), Example(
buildList([0]),
buildList([0]),
buildList([0])
), Example(
buildList([9, 9, 9, 9, 9, 9, 9]),
buildList([9, 9, 9, 9]),
buildList([8, 9, 9, 9, 0, 0, 0, 1])
)]
solve = Solution()
for i, example in enumerate(examples):
ans = solve.addTwoNumbers(example.l1, example.l2)
if check(ans, example.ans):
print(f"PASS: CASE {i}")
else:
print(f"FAIL: CASE {i}")
if __name__ == "__main__":
main()