C# implementation


  • 1
    C

    C# implementation

            public ListNode AddTwoNumbers(ListNode l1, ListNode l2)
            {
                int carry = 0;
                ListNode dummy = new ListNode(0);
                ListNode pre = dummy;
    
                while (l1 != null || l2 != null || carry == 1)
                {
                    int sum = (l1 == null ? 0 : l1.val) + (l2 == null ? 0 : l2.val) + carry;
                    carry = sum < 10 ? 0 : 1;
                    pre.next = new ListNode(sum % 10);
                    pre = pre.next;
    
                    if (l1 != null)
                    {
                        l1 = l1.next;
                    }
    
                    if (l2 != null)
                    {
                        l2 = l2.next;
                    }
                }
    
                return dummy.next;
            }
    

  • 0
    J

    Looks good. Very close to what I did, but yours is more succinct. I used a separate operation at the end to handle the carry being greater than 0. I like your choice for readability.

    One thing I would note for the carry is that you do not need to use a ternary operation. Integer math will round down, so you can just divide by 10:

    carry = sum / 10;
    

Log in to reply
 

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