-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path2.两数相加.py
51 lines (46 loc) · 1.04 KB
/
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
48
49
50
'''
Author: Catherine Xiong
Date: 2022-12-28 17:11:36
LastEditTime: 2022-12-28 17:15:22
LastEditors: Catherine Xiong
Description:
'''
"""
Date: 2022-12-19 14:22:07
LastEditors: yhxiong
LastEditTime: 2022-12-19 14:44:11
Description:
"""
#
# @lc app=leetcode.cn id=2 lang=python
#
# [2] 两数相加
#
# @lc code=start
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
carry = 0
root = n = ListNode(0)
while l1 or l2 or carry:
v1 = v2 = 0
if l1:
v1 = l1.val
l1 = l1.next
if l2:
v2 = l2.val
l2 = l2.next
carry, val = divmod(v1+v2+carry, 10)
n.next = ListNode(val)
n = n.next
return root.next
# @lc code=end