/// "两数相加"
/**
* Definition for singly-linked list.
* public class ListNode {
* public var val: Int
* public var next: ListNode?
* public init() { self.val = 0; self.next = nil; }
* public init(_ val: Int) { self.val = val; self.next = nil; }
* public init(_ val: Int, _ next: ListNode?) { self.val = val; self.next = next; }
* }
*/
public class ListNode {
public var val: Int
public var next: ListNode?
public init() { self.val = 0; self.next = nil; }
public init(_ val: Int) { self.val = val; self.next = nil; }
public init(_ val: Int, _ next: ListNode?) { self.val = val; self.next = next; }
}
class Solution {
func addTwoNumbers(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? {
let result = ListNode()
var lH = l1
var rH = l2
var head = result
var carry = 0
while lH != nil || rH != nil {
let sum = (lH?.val ?? 0) + (rH?.val ?? 0)
carry = sum / 10
head.next = ListNode(sum % 10)
head = head.next!
lH = lH?.next
rH = rH?.next
}
if carry > 0 {
head.next = ListNode(carry)
}
return head.next
}
}
网友评论