My Java Recursion Solution


  • 0
    K
    public class Solution {
        public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            if(l1!=null&&l2!=null){
                l1.val+=l2.val;
                if(l1.val>=10){
                    if(l1.next==null)   l1.next=new ListNode(l1.val/10);
                    else    l1.next.val+=l1.val/10;
                    l1.val%=10;
                }
                l1.next=addTwoNumbers(l1.next, l2.next);
                return l1;
            }else if(l1==null&&l2==null) return null;
            else {
                if(l1==null) l1=l2;
                if(l1.val<10) return l1;
                else {
                    if(l1.next==null){
                        l1.next=new ListNode(l1.val/10);
                        l1.val %=10;
                    }else{
                        l1.next.val+=l1.val/10;
                        l1.val%=10;
                        l1.next = addTwoNumbers(l1.next, null);
                    }
                    return l1;
                }
            }
        }
    }

Log in to reply
 

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