My recursive solution in Java


  • 0
    F

    public class Solution {

    public static int carry=0;
    
    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        
        ListNode l3 = new ListNode(0);
        if ((l1==null) && (l2==null)){
            if(carry>0) {
                l3.val = carry;
                carry=0;
                return l3;
            }
            carry = 0;
            return null;
        }
        
        int x=carry;
        
        if (l1 != null){
            x=x+l1.val;
        }
        
        if (l2 != null){
            x=x+l2.val;
        }
        
        l3.val = x % 10;
        carry = x/10;
        ListNode more = addTwoNumbers(l1 == null ? null : l1.next,
                                l2 == null ? null : l2.next);
        l3.next = more;
        
        return l3;
    }
    

    }


Log in to reply
 

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