C# Solution


  • 0
    public ListNode AddTwoNumbers(ListNode l1, ListNode l2) {
            int carrier = 0, tempResult = 0;
            ListNode dummyNode = new ListNode(-1), previousNode;
            previousNode = dummyNode;
            
            while (l1 != null || l2 != null)
            {
                if (l1 != null)
                    tempResult += l1.val;
                
                if (l2 != null)
                    tempResult += l2.val;
                
                if (carrier != 0)
                {
                    tempResult += carrier;
                    carrier = 0;
                }
                
                if (tempResult >= 10)
                {
                    tempResult = tempResult % 10;
                    carrier = 1;
                }
                
                previousNode.next = new ListNode(tempResult);
                previousNode = previousNode.next;
                
                tempResult = 0;
                if (l1 != null)
                    l1 = l1.next;
                if (l2 != null)
                    l2 = l2.next;
            }
            
            if (carrier > 0)
                previousNode.next = new ListNode(1);
            
            return dummyNode.next;
        }

Log in to reply
 

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