C# simple solution


  • 0
    0
    public ListNode AddTwoNumbers(ListNode l1, ListNode l2) 
    {
        if (l1 == null) return l2;
        if (l2 == null) return l1;
            
        ListNode dummy = new ListNode(0),
                 cur = dummy;
        int carry = 0;
        while (l1 != null || l2 != null)
        {
            int val = carry;
            carry = 0;
            if (l1 != null) 
            {
                val += l1.val;
                l1 = l1.next;
            }
    
            if (l2 != null)
            {
                val += l2.val;
                l2 = l2.next;
            }
                
            if (val > 9) 
            {
                val -= 10;
                carry = 1;
            }
                
            cur.next = new ListNode(val);
            cur = cur.next;
        }
            
        if (carry == 1)
        {
            cur.next = new ListNode(1);
        }
            
        return dummy.next;
    }
    

Log in to reply
 

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