Java solution got "Last executed input: [0], [0]"


  • 0
    Z

    below is my code, could someone help me fix it. I ran test cases [3, 9, 8] + [5, 7, 8, 9] = [8, 6, 7, 0, 1] and [0] + [0] = [0]. both passed.

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    
    		boolean overTen = false;
    		ListNode result = l1;
    		ListNode previous = l1;
    
    		if (l1 == null) return l2;
    		if (l2 == null) return l1;
    
    		while (l1 != null) {
    			if (l2 != null) {
    				int tmpVal = l1.val + l2.val + (overTen ? 1 : 0);
    				l1.val = tmpVal %10;
    				overTen = tmpVal / 10 > 0;
    			}
    			else if (overTen) {
    				overTen = (l1.val + 1 ) / 10 > 0;
    				l1.val = (l1.val + 1) %10;
    			}
    			else {
    				return result;
    			}
    			previous = l1;
    			l1 = l1.next;
    			l2 = l2.next;
    		}
    
    		previous.next = l2;
    		while (l2 != null) {
    			if (overTen) {
    				int tmp = (overTen ? 1 : 0) + l2.val;
    				l2.val = tmp % 10;
    				overTen = tmp / 10 > 0;
    				previous = l2;
    				l2 = l2.next;
    			}
    		}
    		if (overTen) {
    			ListNode last = new ListNode(1);
    			previous.next = last;
    		}
    
    		return result;
    	}

Log in to reply
 

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