leetcode系列 - Add Two Numbers (Medium)

題目簡介

原文: 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.node

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

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8git

譯: 有兩個包含非負整數的鏈表,這兩個鏈表也是非空的。數字倒序存儲而且它們每一個節點包含一個數字。分別對兩個鏈表的每一個數字相加,並將結果存在一個鏈表中返回。
你能夠假設兩個鏈表中不包含任何前導零(leading zero),數字0除外。swift

Swift (version 3.1):

func addTwoNumbers(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? {
        var sum = 0
        var result:ListNode? = ListNode(0)
        var sums = result

        var temp1 = l1
        var temp2 = l2

        while temp1 != nil || temp2 != nil || sum != 0 {
            if temp1 != nil {
                sum += temp1!.val
                temp1 = temp1?.next
            }

            if temp2 != nil {
                sum += temp2!.val 
                temp2 = temp2?.next
            }
            sums?.next = ListNode(sum % 10)
            sums = sums?.next
            sum = sum/10
        }
        return result?.next 
    }複製代碼

Python (version 3.5):

def addTwoNumbers(self, l1, l2):
        result = temp = ListNode(0)
        sum = 0
        while l1 or l2 or sum:
            if l1:
                sum += l1.val
                l1 = l1.next
            if l2:
                sum += l2.val
                l2 = l2.next
            temp.next = ListNode(sum%10)
            temp = temp.next
            sum = sum/10
        return result.next複製代碼
相關文章
相關標籤/搜索