My java solution 3ms beats 98.68% of java submission


  • 0
    Y
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    	if (l1 == null)
    		return l2;
    	if (l2 == null)
    		return l1;
    	int temp = 0;
    	ListNode p = l1;
    	ListNode q = l2;
    	ListNode longList = l1;
    	ListNode la = l1;
    	while (p != null && q != null) {
    		p = p.next;
    		q = q.next;
    	}
    	if (q == null) {
    		q = l1;
    		p = l2;
    		longList = l1;
    	} else {
    		q = l2;
    		p = l1;
    		longList = l2;
    	}
    	while (p != null && q != null) {
    		if (p.val + q.val + temp >= 10) {
    			q.val = p.val + q.val + temp - 10;
    			temp = 1;
    		} else {
    			q.val = q.val + p.val + temp;
    			temp = 0;
    		}
    		p = p.next;
    		q = q.next;
    	}
    	while (q != null) {
    		if (q.val + temp >= 10) {
    			q.val = q.val + temp - 10;
    			temp = 1;
    		} else {
    			q.val = q.val + temp;
    			temp = 0;
    		}
    		q = q.next;
    	}
    	if (temp == 1) {
    		ListNode last = new ListNode(1);
    		last.next = null;
    		p = longList;
    		while (p != null)
    			p = p.next;
    		la = p;
    		la.next = last;
    	}
    
    	return longList;
    }

  • 1
    5
    1. unfriendly code style
    2. changed the value of input
    3. redundent variables

  • 4
    L

    @Youed Line 61: java.lang.NullPointerException when the input is [5][5]


Log in to reply
 

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