LeetCode2:Add Two Numbers
阿新 • • 發佈:2019-01-03
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.
LeetCode:連結
有兩個連結串列,分別是逆序了的十進位制數字。現在要求兩個十位數字的和,要求返回的結果也是連結串列。
可以採用一個進位carry方便的完成一次遍歷得出結果。
兩個要注意的地方:如果列表長度不相等;如果列表相加完成最後仍有進位位。
# 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 """ head = ListNode(0) dummy = head # 進位標誌 carry = 0 while l1 and l2: add = l1.val + l2.val + carry # 是否有進位 carry = 1 if add >= 10 else 0 # 必須是定義一個結點 dummy.next = ListNode(add % 10) dummy = dummy.next l1, l2 = l1.next, l2.next # 如果列表長度不相等 l = l1 if l1 else l2 while l: add = l.val + carry carry = 1 if add >= 10 else 0 dummy.next = ListNode(add % 10) dummy = dummy.next l = l.next # 如果列表相加完成最後仍有進位位 if carry: dummy.next = ListNode(1) return head.next