C# solution


  • 0
    K
    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     public int val;
     *     public ListNode next;
     *     public ListNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public ListNode AddTwoNumbers(ListNode l1, ListNode l2) {
            
            int sum = 0;
            int rem = 0;
            int val = 0;        
            ListNode result = new ListNode(0);
            ListNode prev = result;
    
            for (int i =0;l1!= null || l2!=null;i++)
            {
                sum = 0;
                if (l1 != null)
                    sum += l1.val;
                if (l2 != null)
                    sum += l2.val;
        
                sum += rem;
                
                if (sum >= 10)
                {
                    rem = 1;
                    val = sum-10;
                }
                else
                {
                    rem = 0;
                    val = sum;
                }
                ListNode node = new ListNode(val);
                if (i==0) result.next = node;
                prev.next = node;
                prev = prev.next;
                
                if (l1 != null) l1 = l1.next;
                if (l2 != null) l2 = l2.next;
            }
            if (rem > 0)
            {
                ListNode node = new ListNode(rem);
                prev.next = node;
            }
            return result.next;
        }
    }
    

Log in to reply
 

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