-
Notifications
You must be signed in to change notification settings - Fork 0
/
2.两数相加.py
48 lines (35 loc) · 968 Bytes
/
2.两数相加.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
#
# @lc app=leetcode.cn id=2 lang=python3
#
# [2] 两数相加
#
# @lc code=start
# type 'a list = Nil | Cons of 'a * 'a list
# class listNode:
# def __init__(self, val=0, next=None):
# self.val = x
# self.next = None
# class list:
# def __init__(self, head=None):
# self.head = head
# 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: ListNode, l2: ListNode) -> ListNode:
carry = 0
out = result = ListNode(0)
while l1 or l2 or carry:
if l1:
carry += l1.val
l1 = l1.next
if l2:
carry += l2.val
l2 = l2.next
result.next = ListNode(carry % 10)
result = result.next
carry //= 10
return out.next
# @lc code=end