Concise Simple Java Solution


  • 0
    M
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    
    	ListNode previous = new ListNode(-1);
    	ListNode head = previous;
    	int contribute = 0;
    	while (l1 != null || l2 != null || contribute == 1) {
    		int sum = (l1 == null ? 0 : l1.val) + (l2 == null ? 0 : l2.val)
    				+ contribute;
    		ListNode current;
    		if (sum > 9) {
    			current = new ListNode(sum - 10);
    			contribute = 1;
    		} else {
    			current = new ListNode(sum);
    			contribute = 0;
    		}
    		l1 = l1 == null ? null : l1.next;
    		l2 = l2 == null ? null : l2.next;
    		previous.next = current;
    		previous = current;
    	}
    
    	return head.next;
    
    }

Log in to reply
 

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