My Swift solution


  • 0
    O
    func +(_ lhs: ListNode?, _ rhs: ListNode?) -> Int {
        return (lhs?.val ?? 0) + (rhs?.val ?? 0)
    }
    
    class Solution {
        
        func addTwoNumbers(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? {
            var first = l1, second = l2
            let head = ListNode(0)
            var current = head
            var carry = 0
            while first != nil || second != nil || carry != 0 {
                (current.next, carry) = nextNode(first, second, carry: carry)
                nextStep(&first, &second, current: &current)
            }
            return head.next
        }
        
        private func nextNode(_ first: ListNode?, _ second: ListNode?, carry: Int) -> (ListNode?, Int) {
            let result = first + second + carry
            return (ListNode(result % 10), result / 10)
        }
        
        private func nextStep(_ first: inout ListNode?, _ second: inout ListNode?, current: inout ListNode) {
            current = current.next!
            first = first?.next
            second = second?.next
        }
        
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.