My 6 lines Java solution(Recursive)


  • 0
    L
    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            if(l1 == null || l2 == null)return (l1 == null)?l2:l1;
            int val = l1.val + l2.val;
            ListNode l3 = new ListNode(val%10);
            l3.next = addTwoNumbers(l1.next, l2.next);
            if(val > 9)l3.next = addTwoNumbers(new ListNode(1), l3.next);
            return l3;
        }
    }
    

Log in to reply
 

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