Recursion method is quite simple.
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
return helper(l1,l2,0);
}
private ListNode helper(ListNode l1, ListNode l2, int carry) {
if (l1==null && l2==null && carry == 0) return null;
int sum = 0;
if (l1 != null) {
carry += l1.val;
l1=l1.next;
}
if (l2 != null) {
carry += l2.val;
l2=l2.next;
}
ListNode curr = new ListNode(carry%10);
carry = carry/10;
curr.next = helper(l1,l2,carry);
return curr;
}
No comments:
Post a Comment