Add Two Numbers
Solution in go
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
    dummy := &ListNode{}
    tail := dummy
    carry := 0

    for l1 != nil || l2 != nil {
        result := carry
        if l1 != nil {
            result += l1.Val
        }
        if l2 != nil {
            result += l2.Val
        }

        remainder := result % 10
        carry = result / 10

        node := &ListNode{Val: remainder}
        tail.Next = node
        tail = node

        if l1 != nil {
            l1 = l1.Next
        }
        if l2 != nil {
            l2 = l2.Next
        }             
    }

    if carry != 0 {
        tail.Next = &ListNode{Val:carry}
    }

    return dummy.Next
}
    TheDeveloperCafe © 2022-2024