Add Two Numbers

问题描述

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

示例

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

算法思路

在这个问题中,有两种解决思路,第一种是先将输入的链表计算结果转换成字符串,再转成链表输出;第二种是直接采用链表操作。总的来说,第一种方法更易于理解,执行效率更高(runtime is 116ms),第二种方法更加复杂,耗时更长(runtime is 288ms),所以推荐使用方法一。

代码实现(Python3)

方法一:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution:
def addTwoNumbers(self, l1, l2):
twoSum = str(int(self.getNumber(l1)) + int(self.getNumber(l2)))
return self.constructList(twoSum)

def getNumber(self, head):
current, res = head, []
while current:
res.append(str(current.val))
current = current.next
return ''.join(res[::-1]) # reverse res

def constructList(self, num):
head = ListNode(int(num[-1])) # get the last element
current = head
for i in range(len(num) - 2, -1, -1): # range(start, stop, step)
node = ListNode(int(num[i]))
current.next = node
current = current.next
return head

方法二:

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
51
52
53
54
55
# 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
"""

# Carry over place holder.
carry = 0

# Create a dummy head, tail node to keep track of the start and end of the list
dummy_head = tail = ListNode(0)

# While there are elements in either list we add them
while l1 or l2:

# Get the two element values, if there is not a node use 0
num_one = l1.val if l1 else 0
num_two = l2.val if l2 else 0

# Get the new total with two numbers plus the carry over
new_sum = num_one + num_two + carry

# Check to see if the number will create a carry
if new_sum > 9:
# Set the tail node equal to the new node.
tail.next = ListNode(new_sum - 10)
# Set a carry because the number was larger than 10
carry = 1
else:
tail.next = ListNode(new_sum)
carry = 0

# Set the tail node to the new tail.
tail = tail.next

# Set the current nodes to the next number
if l1:
l1 = l1.next
if l2:
l2 = l2.next

# Once the adding has been completed if there is still a carry append a new node
if carry:
tail.next = ListNode(carry)

# Return the first number set, dummy head was just a place holder. The tail would point to the last node and not the first number in the linked list.
return dummy_head.next
参考资料
  1. https://stackoverflow.com/questions/31633635/what-is-the-meaning-of-inta-1-in-python What is the meaning of “int(a[::-1])” in Python?
  2. https://stackoverflow.com/questions/930397/getting-the-last-element-of-a-list-in-python Getting the last element of a list in Python
  3. https://www.pythoncentral.io/pythons-range-function-explained/ Python’s range() Function Explained
  4. https://leetcode.com/problems/add-two-numbers/ Add Two Numbers

Add Two Numbers
https://xiepeng21.cn/posts/64c8f80f/
作者
Peng Xie
发布于
2018年10月6日
许可协议