Cleanest and Easiest Recursive 10 liner Java solution


  • 0
    A

    This is a clean and easily understandable recursive java solution.
    Accepted by leetcode

    public class Solution {
        public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        
            return addTwoNumbersRecursive(l1, l2, 0);
        }
        
        public static ListNode addTwoNumbersRecursive(ListNode l1, ListNode l2, int carry) {
            
            if(l1 == null && l2 == null)    return carry != 0 ? new ListNode(carry) : null;
    
            int first = 0;
            int second = 0;
    
            if(l1 != null)  first = l1.val;
    
            if(l2 != null)  second = l2.val;
    
            int add = first + second + carry;
            int newCarry = add / 10;
    
            ListNode toReturn = new ListNode(add % 10);
            toReturn.next = addTwoNumbersRecursive(l1 == null ? null : l1.next, l2 == null ? null : l2.next, newCarry);
    
            return toReturn;
        }
    }
    

Log in to reply
 

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