My simple java solution


  • 0
    X
    public class Solution {
        public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            return add(l1,l2,0);
        }
        
        public ListNode add(ListNode l1, ListNode l2, int carry){
            if(l1==null && l2==null && carry==0)  return null;
            
            ListNode result=new ListNode(0);
            int val=carry;
            
            if(l1!=null) val+=l1.val;
            if(l2!=null) val+=l2.val;
            
            result.val=val%10;
            int new_carry= val>9?1:0;
            
            if(l1!=null||l2!=null){
                ListNode more=add(l1==null?l1:l1.next,l2==null?l2:l2.next,new_carry);
                result.next=more;
            }
            
            return result;
        }
    }

Log in to reply
 

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