Accepted Java solution


  • 0
    V

    public class Solution {

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    
        ListNode list = new ListNode(0);
        ListNode result = list;     
        int add = 0;
        
        while(l1 != null && l2 != null){
          list.val = (l1.val + l2.val + add) % 10;
          add = (l1.val + l2.val + add) / 10;
          l1 = l1.next;
          l2 = l2.next;
          
          if(l1 != null || l2 != null){
               list.next = new ListNode(0);
               list = list.next;
          }
        }
        
        while(l1 != null && l2 == null){
            list.val = (l1.val + add) % 10;
            add = (l1.val + add) / 10;
            l1 = l1.next;
            
            if(l1 != null || l2 != null){
                list.next = new ListNode(0);
                list = list.next;
          }
        }
        
        while(l1 == null && l2 != null){
            list.val = (l2.val + add) % 10;
            add = (l2.val + add) / 10;
            l2 = l2.next;
            
            if(l1 != null || l2 != null){
                list.next = new ListNode(0);
                list = list.next;
          }
        }
        if(add == 1){
            list.next = new ListNode(0);
            list = list.next;
            list.val = 1;
        }
        
        return result;
    }
    

    }


  • 3
    X
    public class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode dummy = new ListNode(Integer.MIN_VALUE);
        int c = 0;
        ListNode cur = dummy;
        while(l1!=null || l2!=null || c!=0){
            int l2Val = 0;
            int l1Val = 0;
            if(l1!=null){
                l1Val = l1.val;
                l1 = l1.next;
            }
            if(l2!=null){
                l2Val = l2.val;
                l2 = l2.next;
            }
           
            int sum = l1Val+l2Val+c;
            int cursum = sum>=10?sum-10:sum;
            c = sum>=10?1:0;
            ListNode newNode = new ListNode(cursum);
            cur.next = newNode;
            cur = cur.next;
          
        }
        return dummy.next;
    }
    

    }


Log in to reply
 

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