3ms Java code for Add Two Numbers


  • 1
    A

    public class Solution {

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        if(l1 == null && l2 == null){
            return null;
        }else if(l1 == null){
            return l2;
        }else if(l2 == null){
            return l1;
        }else{
            int len1 = 0;
            int len2 = 0;
            ListNode tmp1 = l1;
            ListNode tmp2 = l2;
            ListNode tmp = null;
            while(tmp1 != null){
                len1++;
                tmp1 = tmp1.next;
            }
            while(tmp2 != null){
                len2++;
                tmp2 = tmp2.next;
            }
            if(len2 > len1){
                tmp = l1;
                l1 = l2;
                l2 = tmp;
            }
            int jw = 0;
            int sum = 0;
            ListNode res = l1;
            ListNode oldTail = null;
            while(l2 != null){
                sum = l2.val + l1.val + jw;
                if(sum < 10){
                    if(l1.next == null){
                        oldTail = l1;
                    }
                    l1.val = sum;
                    l1 = l1.next;
                    l2 = l2.next;
                    jw = 0;
                }else{
                    if(l1.next == null){
                        oldTail = l1;
                    }
                    l1.val = sum - 10;
                    jw = 1;
                    l1 = l1.next;
                    l2 = l2.next;
                }
            }
            while(l1 != null){
                sum = l1.val + jw;
                if(sum < 10){
                    if(l1.next == null){
                        oldTail = l1;
                    }
                    l1.val = sum;
                    l1 = l1.next;
                    jw = 0;
                }else{
                    if(l1.next == null){
                        oldTail = l1;
                    }
                    l1.val = sum - 10;
                    jw = 1;
                    l1 = l1.next;
                }
            }
            if(jw == 1){
                ListNode lastNode = new ListNode(1);
                oldTail.next = lastNode;
            }
            return res;
        }
    }
    

    }


Log in to reply
 

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