Accept Java solution of Add Two Numbers


  • 1
    V

    public class Solution {

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        if(l1 == null){
            return l2;
        }
        if(l2 == null){
            return l1;
        }
        
        ListNode dummy = new ListNode((l1.val + l2.val) % 10);
        int add = (l1.val + l2.val) / 10;
        ListNode result = dummy;
        
        l1 = l1.next;
        l2 = l2.next;
        
        while(l1 != null && l2 != null){
            ListNode generateNode = new ListNode((l1.val + l2.val + add) % 10);
            add = (l1.val + l2.val + add) / 10;
            dummy.next = generateNode;
            dummy = dummy.next;
            l1 = l1.next;
            l2 = l2.next;
        }
        
        if(l1 != null && l2 == null){
            if(add == 1){
                dummy.next = listAddOne(l1, 1);
            }else{
                dummy.next = l1;
            }
        }
        
        if(l1 == null && l2 != null){
            if(add == 1){
                dummy.next = listAddOne(l2, 1);
            }
            else{
                dummy.next = l2;
            }
        }
        
        if(l1 == null && l2 == null){
            if(add == 1){
                dummy.next = new ListNode(1);
            }
        }
        
        return result;
    }
    
    private ListNode listAddOne(ListNode node, int num){
        ListNode dd = new ListNode(1);
        dd.next = node;
        ListNode nodeDummy = node;
        
        if(num == 0){
            return node;
        }
        
        int tmp = 0;
        while(num == 1 && dd.next != null){
           tmp = (dd.next.val + num) % 10;
           num = (dd.next.val + num) / 10;
           dd.next.val = tmp;
           dd = dd.next;
        }
        
        if(num == 1){
            ListNode endNode = new ListNode(1);
            dd.next = endNode;
        }      
        return nodeDummy;
    }
    

    }


Log in to reply
 

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