Golang solution example, takes 48ms


  • 1
    func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
        head := &ListNode{}
        res := head // hold an address of the head
        carryOver, sum := 0, 0
        for l1 != nil || l2 != nil {
            head.Next = &ListNode{}
            head = head.Next
            
            sum = carryOver
            if l1 != nil {
                sum += l1.Val
                l1 = l1.Next
            }
            if l2 != nil {
                sum += l2.Val
                l2 = l2.Next
            }
            
            head.Val, carryOver = sum % 10, sum / 10
        }
        
        // handle the last carry over
        if carryOver == 1 {
            head.Next = &ListNode{Val:1}
        }
        
        return res.Next
    }
    

    Straight forward.
    Time complexity: O(N)
    Space complexity: O(N)
    While N is a bigger length of either l1 or l2.


Log in to reply
 

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