Recursive solution in Java


  • 0
    S
    public ListNode addTwoNumbers(ListNode l1, ListNode l2, int carry) {
    		if (l1 == null && l2 == null)
    			return (carry == 0 ? null : new ListNode(carry));
    		int value = (l1 == null ? 0 : l1.val) + (l2 == null ? 0 : l2.val)+ carry;
    		ListNode result = new ListNode((value) % 10);
    		carry = (value) / 10;
    		result.next = addTwoNumbers(l1 == null ? null : l1.next, l2 == null ? null : l2.next, carry);
    		return result;
    	}

Log in to reply
 

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