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
}
Subscribe via email

Get notified once/twice per month when new articles are published.

Copyright © 2022 - 2024 TheDeveloperCafe.
The Go gopher was designed by Renee French.