Java Solution with O(1) Space and O(n) Solution beat 94%


  • 0
    T
            if (l1 == null) return l2;
            if (l2 == null) return l1;
            int sum = 0;
            ListNode h1 = l1;
            ListNode h2 = l2;
            while (h1.next != null && h2.next !=null) {
                sum += h1.val + h2.val;
                h1.val = sum%10;
                h2.val = sum%10;
                sum = sum >= 10? 1 : 0;
                h1 = h1.next;
                h2 = h2.next;
            }
    
            if (h1.next == null && h2.next == null){
                sum += h1.val + h2.val;
                h1.val = sum%10;
                if ( sum>=10) {
                    h1.next =new ListNode(1);
                }
                return l1;
            }
            if (h1.next == null) {
                sum += h1.val;
                solve (sum , h2);
                return l2;
            }else {
                sum += h2.val;
                solve(sum, h1);
                return l1;
            }
        }
    
        private void solve(int sum, ListNode h) {
            while (sum != 0) {
                sum += h.val;
                h.val = sum%10;
                sum = sum >= 10? 1 : 0;
                if (h.next != null) {
                    h = h.next;
                }else {
                    h.next = sum==1? new ListNode(1):null;
                    return;
                }
            }
        }
    

    we record the result in the longer list,then return the longer one for result


Log in to reply
 

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