[Leetcode] Add Two Numbers
2017-12-31 本文已影响0人
Azurelore
原题:
https://leetcode.com/problems/add-two-numbers/description/
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.
Example
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
分析:
明显的链表问题。非负整数说明不用考虑符号和小数点,每个节点代表一位0-9的数字。并且输入不存在0开头的情况。
唯一需要注意的是输入的两个链表长度可能不同,迭代循环需要小心。
再有进位问题:即便两个链表已经算完,进位上有值,仍然需要在和链表中生成新节点。例如:(5) + (5) = (0 -> 1)
解题:
第一版
# 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
"""
sentinel = cur = ListNode(0)
carry = 0
while l1 != None or l2 != None or carry != 0:
a = l1.val if l1 != None else 0
b = l2.val if l2 != None else 0
x = a + b + carry
carry = x // 10
x %= 10
node = ListNode(x)
cur.next = node
cur = cur.next
if l1 != None:
l1 = l1.next
if l2 != None:
l2 = l2.next
return sentinel.next
Runtime: 148 ms
第二版:简化代码。
# 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
"""
sentinel = cur = ListNode(0)
carry = 0
while l1 != None or l2 != None or carry != 0:
if l1:
carry += l1.val
l1 = l1.next
if l2:
carry += l2.val
l2 = l2.next
cur.next = ListNode(carry % 10)
carry //= 10
cur = cur.next
return sentinel.next
Runtime: 119 ms 运行速度略微提升