Simple Solution in C#


  • 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 carry = 0;
            ListNode newLn = new ListNode(0);
            ListNode root = newLn;
            
            while(l1 != null || l2 != null || carry == 1 )
            {        
                int l1val = 0;
                int l2val = 0;
                int sum = 0;
                
                if(l1 != null && l1.val != null)
                    l1val = l1.val;
                
                if(l2 != null && l2.val != null)
                    l2val= l2.val;
                
                sum = l1val + l2val + carry;
    
                if(carry == 1)
                {
                   carry = 0;
                }
    
                if(sum > 9)
                {
                    carry = 1;
                    sum = sum % 10;
                }
    
                newLn.next = new ListNode(sum); 
                newLn = newLn.next;
                
                if(l1 != null && l1.next != null)
                   l1 = l1.next;
                else
                    l1=null;
                
                if(l2 != null && l2.next != null)
                   l2 = l2.next;
                 else
                    l2=null;
            } 
            
            return root.next;
        }
    }
    
    

Log in to reply
 

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