Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // MARK: - 2. Add Two Numbers
- func addTwoNumbers(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? {
- var l1 = l1
- var l2 = l2
- var result = ListNode()
- var current: ListNode? = result
- var additional = 0
- // Надо еще обработать случай когда 7+8 и остается добавка
- while l1 != nil || l2 != nil || additional != 0 {
- var v1 = l1 != nil ? l1?.val : 0
- var v2 = l2 != nil ? l2?.val : 0
- // Новое число
- var newVal = v1! + v2! + additional
- // Если newVal > 10
- additional = newVal / 10
- newVal = newVal % 10
- current?.next = ListNode(newVal)
- // Обновим указатели
- current = current?.next
- l1 = l1 != nil ? l1?.next : nil
- l2 = l2 != nil ? l2?.next : nil
- }
- return result.next
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement