Easy follow Java solution


  • 0
    J
    /**
     * 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) return l2;
          if(l2==null) return l1;
          // hold new List
          ListNode newList = new ListNode(0);
          ListNode hold = newList;
          
          int carry = 0;
                 
          while(l1!=null&&l2!=null){
              int sum = l1.val+l2.val+carry;
              carry = sum/10;
              sum = sum%10;
              newList.next = new ListNode(sum);
              newList = newList.next;
              l1 = l1.next;
              l2 = l2.next;
          }   
          
          while(l1!=null){
              int oneValue = l1.val+carry;
              carry = oneValue/10;
              oneValue = oneValue%10;
              newList.next = new ListNode(oneValue);
              l1 = l1.next;
              newList = newList.next;
          }
          while(l2!=null){
              int twoValue = l2.val+carry;
              carry = twoValue/10;
              twoValue = twoValue%10;
              newList.next = new ListNode(twoValue);
              l2 = l2.next;
              newList = newList.next;
          }
          
          if(carry>0){
              newList.next = new ListNode(carry);
              return hold.next;
          }
          
          return hold.next;
          
        }
    }

Log in to reply
 

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