原題:
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.
分析:
明顯的鏈表問題。非負(fù)整數(shù)說明不用考慮符號(hào)和小數(shù)點(diǎn),每個(gè)節(jié)點(diǎn)代表一位0-9的數(shù)字。并且輸入不存在0開頭的情況。
唯一需要注意的是輸入的兩個(gè)鏈表長(zhǎng)度可能不同,迭代循環(huán)需要小心。
再有進(jìn)位問題:即便兩個(gè)鏈表已經(jīng)算完,進(jìn)位上有值,仍然需要在和鏈表中生成新節(jié)點(diǎn)。例如:(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
第二版:簡(jiǎn)化代碼。
# 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 運(yùn)行速度略微提升