Swift LeetCode 系列之 2: add-two-numbers

https://leetcode.com/problems/add-two-numbers/description/

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     public var val: Int
 *     public var next: ListNode?
 *     public init(_ val: Int) {
 *         self.val = val
 *         self.next = nil
 *     }
 * }
 */

class Solution {
    func addTwoNumbers(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? {
        
        var l1 = l1
        var l2 = l2
        var sum = 0
        let result = ListNode(0)
        var temp = result
        var remain = 0
        
        while l1 != nil || l2 != nil || remain != 0 {
            sum = remain
            if l1 != nil {
                sum += l1!.val
                l1 = l1?.next
            }
            if l2 != nil {
                sum += l2!.val
                l2 = l2?.next
            }
            remain = sum / 10
            sum = sum % 10
            let node = ListNode(sum)
            temp.next = node
            temp = temp.next!
        }
        return result.next
    }
}


}

    原文作者:TimberTang
    原文地址: https://www.jianshu.com/p/bf13a7727208
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞