Java Recursion Version


  • 0
    U
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        return helper(l1, l2, 0);    
    }
    
    private ListNode helper(ListNode l1, ListNode l2, int carry) {
        if (l1 != null || l2 != null || carry != 0) {
            int sum = (l1 != null ? l1.val : 0) + (l2 != null ? l2.val : 0) + carry;
            int curDigit = sum%10;
            int curCarry = sum/10;
            ListNode newHead = new ListNode(curDigit);
            newHead.next = helper(l1 != null ? l1.next : null, l2 != null ? l2.next : null, curCarry);
            return newHead;
        }
        return null;
    }

Log in to reply
 

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