-
Notifications
You must be signed in to change notification settings - Fork 17
/
add-two-numbers-ii.py
68 lines (51 loc) · 1.65 KB
/
add-two-numbers-ii.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
from typing import Optional
class Number:
def __init__(self, node: Optional[ListNode]) -> None:
self.head = node
def reverse(self) -> None:
node = None
next_node = self.head
while next_node:
next_node.next, next_node, node = node, next_node.next, next_node
self.head = node
def __add__(self, other: "Number") -> "Number":
self.reverse()
other.reverse()
left = self.head
right = other.head
head = ListNode(123)
node = head
carry = 0
while left and right:
node.next = ListNode((left.val + right.val + carry) % 10)
carry = (left.val + right.val + carry) // 10
node = node.next
left = left.next
right = right.next
while left:
node.next = ListNode((left.val + carry) % 10)
carry = (left.val + carry) // 10
node = node.next
left = left.next
while right:
node.next = ListNode((right.val + carry) % 10)
carry = (right.val + carry) // 10
node = node.next
right = right.next
if carry > 0:
node.next = ListNode(carry)
self.reverse()
other.reverse()
result = Number(head.next)
result.reverse()
return result
# Definition for singly-linked list.
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]:
return (Number(l1) + Number(l2)).head