Skip to content

Commit fada831

Browse files
authored
Create 2_ AddTwoNumbers.py3
1 parent bdfca9f commit fada831

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

LinkedList/2_ AddTwoNumbers.py3

+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
# ================================================================================
2+
# LeetCode - Algorithms - 2. Add Two Numbers
3+
# https://leetcode.com/problems/add-two-numbers/description/
4+
#
5+
# Language: Python3
6+
# Author: ConradG
7+
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
8+
# 第一反应竟然是反转后转换成数字进行加法 XD
9+
# 基本的链表操作,不过肯定python小伙伴告知为什么这么慢 T.T
10+
# ================================================================================
11+
12+
# Definition for singly-linked list.
13+
# class ListNode:
14+
# def __init__(self, x):
15+
# self.val = x
16+
# self.next = None
17+
18+
class Solution:
19+
def addTwoNumbers(self, l1, l2):
20+
21+
"""
22+
:type l1: ListNode
23+
:type l2: ListNode
24+
:rtype: ListNode
25+
"""
26+
27+
p = 0
28+
result = t = ListNode(0)
29+
while (l1 or l2 or p > 0):
30+
31+
a = l1.val if l1 != None else 0
32+
b = l2.val if l2 != None else 0
33+
34+
t.next = ListNode((a + b + p) % 10)
35+
t = t.next
36+
37+
l1, l2, p = l1.next if l1 else None, l2.next if l2 else None, (a + b + p) // 10
38+
39+
return result.next
40+
41+
# 1562 / 1562 test cases passed.
42+
# Status: Accepted
43+
# Runtime: 215 ms
44+
# Your runtime beats 40.06 % of python3 submissions.

0 commit comments

Comments
 (0)