C# recursion solution, beats 98.93% of submissions


  • 1
    G
     * Definition for singly-linked list.
     * public class ListNode {
     *     public int val;
     *     public ListNode next;
     *     public ListNode(int x) { val = x; }
     * }
     */
    public class Solution {
        int excess = 0;
        public ListNode AddTwoNumbers(ListNode l1, ListNode l2) {
            var local_l1 = l1;
            var local_l2 = l2;
            if (local_l1 != null || local_l2 != null)
            {
                // if linked list has mismatching number of nodes, we "even them out" by replacing nulls with zeroes
                int x = local_l1 != null ? local_l1.val : 0;
                int y = local_l2 != null ? local_l2.val : 0;
                int z = x + y;
                if (excess > 0) 
                {
                    z += excess; 
                    excess = 0;
                }
                if (z >= 10) 
                {
                    excess = 1;
                    z -= 10;
                }
                return new ListNode(z)
                {
                    next = AddTwoNumbers(local_l1 == null ? null : local_l1.next , local_l2 == null ? null : local_l2.next)
                };
            }
            if (excess > 0)return new ListNode(excess); else return null; 
            // return excess value as next if only 1 node in any linked list 
        }
    }

Log in to reply
 

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