Recursive and iterative solution, Java


  • 1
    S

    Iterative Solution

    public class Solution {
    	public final static int BASE = 10;
    
    	public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    		int sum, low, overflow = 0;
    		ListNode node = new ListNode(0), head = node;
    		while (l1 != null || l2 != null) {
    			sum = (l1 == null ? 0 : l1.val) + (l2 == null ? 0 : l2.val)
    					+ overflow;
    			low = sum % BASE;
    			overflow = sum / BASE;
    			node.next = new ListNode(low);
    			node = node.next;
    			l1 = l1 == null ? null : l1.next;
    			l2 = l2 == null ? null : l2.next;
    		}
    		if (overflow > 0)
    			node.next = new ListNode(overflow);
    		return head.next;
    	}
    }
    

    Recursion Solution

    public class Solution {
    	public final static int BASE = 10;
    
    	public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    		return addTwoNumbers(l1, l2, 0);
    	}
    
    	private ListNode addTwoNumbers(ListNode l1, ListNode l2, int carry) {
    		if (l1 == null)
    			return (carry == 0 ? l2 : addTwoNumbers(new ListNode(carry), l2,
    					0));
    		else if (l2 == null)
    			return (carry == 0 ? l1 : addTwoNumbers(l1, new ListNode(carry),
    					0));
    		else {
    			int sum = l1.val + l2.val + carry;
    			ListNode node = new ListNode(sum % BASE);
    			node.next = addTwoNumbers(l1.next, l2.next, sum / BASE);
    			return node;
    		}
    	}
    }

Log in to reply
 

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