Easy solution in Go


  • 0
    T

    Go is supported now, cheers!

    func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
        carry := 0
        head := new(ListNode)
        cur := head
        for l1 != nil || l2 != nil || carry != 0 {
            n1, n2 := 0, 0
            if l1 != nil {
                n1, l1 = l1.Val, l1.Next
            }
            if l2 != nil {
                n2, l2 = l2.Val, l2.Next
            }
            num := n1 + n2 + carry
            carry = num / 10
            cur.Next = &ListNode{Val:num%10, Next:nil}
            cur = cur.Next
        }
        return head.Next
    }

  • 0
    N

    Use "container/list" package shipped by golang:

    func addTwoNumbers(l1, l2 *list.List) *list.List {
        var carry int
        var er *list.Element
    
        lr := list.New()
        e1 := l1.Front()
        e2 := l2.Front()
    
        for e1 != nil && e2 != nil {
    	    lr.PushBack((e1.Value.(int) + e2.Value.(int) + carry) % 10)
    	    carry = (e1.Value.(int) + e2.Value.(int) + carry) / 10
    
    	    e1 = e1.Next()
    	    e2 = e2.Next()
        }
    
        if e1 != nil {
    	    er = e1
        } else if e2 != nil {
    	    er = e2
        }
    
        for er != nil {
    	    lr.PushBack((er.Value.(int) + carry) % 10)
    	    carry = (er.Value.(int) + carry) / 10
    
    	    er = er.Next()
        }
    
        return lr
    }

  • 0
    T

    thanks for your sharing!


Log in to reply
 

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