12 line java solution


  • 13
    E

    /**

    • Definition for singly-linked list.

    • public class ListNode {

    • int val;
      
    • ListNode next;
      
    • ListNode(int x) {
      
    •     val = x;
      
    •     next = null;
      
    • }
      
    • }
      */
      public class Solution {
      public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
      return addTwoNumbersWithCarryOver(l1,l2,0);
      }

      public ListNode addTwoNumbersWithCarryOver(ListNode l1,ListNode l2, int carryOver){
      if (l1 == null) {
      return carryOver == 0 ? l2 : addTwoNumbersWithCarryOver(new ListNode(carryOver), l2,0);
      }

       if (l2 == null) {
          return carryOver == 0 ? l1 : addTwoNumbersWithCarryOver(l1, new ListNode(carryOver),0);
       }
       
       int sumVal = l1.val + l2.val + carryOver;
       ListNode returnVal = new ListNode(sumVal%10);
       returnVal.next = addTwoNumbersWithCarryOver(l1.next,l2.next, sumVal/10);
       return returnVal;
      

      }
      }


  • 0
    O

    it maybe short, but it takes too much space I think


  • 1
    Y

    I am so stupid. I always admire those who can use recursion...
    can anyone tell me how to learn to use recursion?


  • 0
    C

    Don't be so disappointed. Try to read others's code and practice. You can do it, too.


  • 0
    A

    Just try to think an recursive way yourself you will improve the more you think about it,I was in the same conditions a while back :)


  • 0
    Z

    I feel recursion is more intuitive than loop after read the book call "the little schemer".


  • 0
    Z

    You could be more concise by replacing:

    if (l2 == null) {
       return carryOver == 0 ? l1 : addTwoNumbersWithCarryOver(l1, new ListNode(carryOver),0);
    }
    

    with:

    if (l2 == null) {
       return addTwoNumbersWithCarryOver(l2, l1,carryOver);
    }

  • 0
    S

    Sorry but why would this use more space?


Log in to reply
 

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