1. 程式人生 > 其它 >Codeforces Round #741 (Div. 2), problem: (D1) Two Hundred Twenty One (easy version), 1700

Codeforces Round #741 (Div. 2), problem: (D1) Two Hundred Twenty One (easy version), 1700

給你兩個非空 的連結串列,表示兩個非負的整數。它們每位數字都是按照逆序的方式儲存的,並且每個節點只能儲存一位數字。

請你將兩個數相加,並以相同形式返回一個表示和的連結串列。

你可以假設除了數字 0 之外,這兩個數都不會以 0開頭。

輸入:l1 = [2,4,3], l2 = [5,6,4]
輸出:[7,0,8]
解釋:342 + 465 = 807.
示例 2:

輸入:l1 = [0], l2 = [0]
輸出:[0]
示例 3:

輸入:l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
輸出:[8,9,9,9,0,0,0,1]

來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/add-two-numbers
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。

思路

在l1或l2跑完之前,將他們兩兩相加得到一數

對該數進行處理,%10放入ListNode裡,再/10傳遞到下一位

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution(object):
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        
""" head = None rear = None value = 0 while (l1) or (l2): if l1: value += l1.val l1 = l1.next if l2: value += l2.val l2 = l2.next if rear == None: rear
= ListNode(value%10) value = value/10 head = rear else: rear.next = ListNode(value%10) value = value/10 rear = rear.next if value: rear.next = ListNode(value) return head