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 } }

性能

原文发布于微信公众号 - 大话swift(gh_ca2266b7cab0)

原文发表时间:2019-01-29

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

扫码关注云+社区

领取腾讯云代金券