Golang Solution


  • 1
    H

    Time Complexity: O(max(m,n))

    Space Complexity: O(max(m,n))

    func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
    	dummyNode := ListNode{0, nil}
    	carry := 0
    	current := &dummyNode
    
    	for l1 != nil || l2 != nil {
    		var x, y int
    		if (l1 == nil) {
    			x = 0
    		} else {
    			x = l1.Val;
    		}
    
    		if (l2 == nil) {
    			y = 0
    		} else {
    			y = l2.Val
    		}
    
    		sum := x + y + carry
    
    		current.Next = &ListNode{sum % 10, nil}
    		carry = sum / 10
    
    		current = current.Next
    		if l1 != nil {
    			l1 = l1.Next
    		}
    
    		if l2 != nil {
    			l2 = l2.Next
    		}
    	}
    
    	if carry != 0 {
    		current.Next = &ListNode{1, nil}
    	}
    
    	return dummyNode.Next
    }

Log in to reply
 

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