Skip to content

Instantly share code, notes, and snippets.

@adnan-SM
Created April 29, 2020 06:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adnan-SM/9bc6674c6ab3e5df6f7ee588ade946d4 to your computer and use it in GitHub Desktop.
Save adnan-SM/9bc6674c6ab3e5df6f7ee588ade946d4 to your computer and use it in GitHub Desktop.
Add Numbers
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
return addNumbersHelper(l1, l2, 0);
}
public ListNode addNumbersHelper(ListNode l1, ListNode l2, int carry) {
if(l1 == null && l2 == null && carry == 0) {
return null;
}
int value = carry;
if(l1 != null) {
value += l1.val;
}
if(l2 != null) {
value += l2.val;
}
ListNode result = new ListNode(value%10);
if(l1 != null || l2 != null) {
ListNode more = addNumbersHelper(l1 == null? null: l1.next,l2 == null? null: l2.next, value >= 10? 1:0);
result.next = more;
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment