LintCode Q167 Add Two Numbers in Python

  • Jinhai ZHOU
  • 6 Minutes
  • 2016年11月12日
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
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param l1: the first list
# @param l2: the second list
# @return: the sum list of l1 and l2
# Total Runtime: 267 ms
# 100% test cases passed.
def addLists(self, l1, l2):
# write your code here
return self.addList(l1, l2, 0)
def addList(self, l1, l2, carry):
# l1 or l2 is None and carry == 0
if l1 is None or l2 is None:
if carry == 0:
if l1 is None:
return l2
else:
return l1
else:
if l1 is None and l2 is None:
this_node = ListNode(carry)
return this_node
else:
l1 = l1 if l2 is None else l2 # l1 is not None
sum_val = l1.val + carry
this_val = sum_val%10
carry = sum_val/10
this_node = ListNode(this_val)
next_node = self.addList(l1.next, None, carry)
this_node.next = next_node
return this_node
sum_val = l1.val + l2.val + carry
this_val = sum_val%10
carry = sum_val/10
this_node = ListNode(this_val)
next_node = self.addList(l1.next, l2.next, carry)
this_node.next = next_node
return this_node
知识共享许可协议
本作品采用知识共享署名-相同方式共享 4.0 国际许可协议进行许可。