# LeetCode之两数之和

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

Solutuon

/** * 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 tmp1 = l1 var tmp2 = l2 var stepper = 0 var destListNode: ListNode? while tmp1 != nil || tmp2 != nil { var dest = 0 if(tmp1 != nil){ dest = dest + tmp1!.val tmp1 = tmp1?.next } if(tmp2 != nil){ dest = dest + tmp2!.val tmp2 = tmp2?.next } dest = dest + stepper // print(dest) stepper = Int(dest / 10) if(destListNode == nil){ destListNode = ListNode.init(dest%10) }else{ var tmp = destListNode while tmp?.next != nil { tmp = tmp?.next } tmp?.next = ListNode.init(Int(dest%10)) } } if stepper != 0 { var tmp = destListNode while tmp?.next != nil { tmp = tmp?.next } tmp?.next = ListNode.init(Int(stepper%10)) } return destListNode } }

114 篇文章21 人订阅

0 条评论