-
-
Save tangqiaoboy/af0dc9a45dd309e91436b44b76eab5f1 to your computer and use it in GitHub Desktop.
iOS 面试题(13):求两个链表表示的数的和
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Author: Tang Qiao | |
// GitHub: https://github.com/tangqiaoboy | |
// | |
// Add Two Numbers | |
// https://leetcode.com/problems/add-two-numbers/ | |
private class ListNode { | |
public var val: Int | |
public var next: ListNode? | |
public init(_ val: Int) { | |
self.val = val | |
self.next = nil | |
} | |
} | |
private class Solution { | |
private static func getNodeValue(_ node: ListNode?) -> Int { | |
return node.flatMap { $0.val } ?? 0 | |
} | |
func addTwoNumbers(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? { | |
if l1 == nil || l2 == nil { | |
return l1 ?? l2 | |
} | |
var p1 = l1 | |
var p2 = l2 | |
let result: ListNode? = ListNode(0) | |
var current = result | |
var extra = 0 | |
while p1 != nil || p2 != nil || extra != 0 { | |
var tot = Solution.getNodeValue(p1) + | |
Solution.getNodeValue(p2) + extra | |
extra = tot / 10 | |
tot = tot % 10 | |
let sum:ListNode? = ListNode(tot) | |
current!.next = sum | |
current = sum | |
p1 = p1.flatMap { $0.next } | |
p2 = p2.flatMap { $0.next } | |
} | |
return result!.next | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment