Skip to content

Instantly share code, notes, and snippets.

@engtomhat
Created July 24, 2017 17:18
Show Gist options
  • Save engtomhat/493995c2cb72a1ea3420267d0147b7f6 to your computer and use it in GitHub Desktop.
Save engtomhat/493995c2cb72a1ea3420267d0147b7f6 to your computer and use it in GitHub Desktop.
Add Two Numbers
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class AddTwoNumbers {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode iterator1 = l1;
ListNode iterator2 = l2;
ListNode solution = new ListNode(-1);
ListNode solutionIterator = solution;
int carry = 0;
int sum = 0;
while(iterator1 != null || iterator2 != null) {
sum += carry;
if(iterator1 != null) {
sum += iterator1.val;
iterator1 = iterator1.next;
}
if(iterator2 != null) {
sum += iterator2.val;
iterator2 = iterator2.next;
}
if(solutionIterator.val >= 0) {
solutionIterator.next = new ListNode(-1);
solutionIterator = solutionIterator.next;
}
solutionIterator.val = sum % 10;
carry = sum / 10;
sum = 0;
}
if(carry > 0) {
solutionIterator.next = new ListNode(carry);
}
return solution;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment