-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path2.AddTwoNumbers.py
More file actions
40 lines (39 loc) · 1.1 KB
/
2.AddTwoNumbers.py
File metadata and controls
40 lines (39 loc) · 1.1 KB
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
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
:note: 先遍历链表,将数字转换成整数,然后两个整数求和,最后将整数和存入链表中,注意需要用pre指向前一个节点
"""
num1 = l1.val
num2 = l2.val
rank = 10
while(l1.next != None):
l1 = l1.next
num1 += l1.val * rank
rank *= 10
rank = 10
while(l2.next != None):
l2 = l2.next
num2 += l2.val * rank
rank *= 10
num = num1 + num2
L = pre = None
if num == 0:
L = ListNode(0)
return L
while(num != 0):
cur = ListNode(num % 10)
num /= 10
if pre != None:
pre.next = cur
pre = cur
else :
L = pre = cur
return L