Skip to content

Instantly share code, notes, and snippets.

@linzhp
Created March 23, 2013 21:40
Show Gist options
  • Save linzhp/5229466 to your computer and use it in GitHub Desktop.
Save linzhp/5229466 to your computer and use it in GitHub Desktop.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
// Start typing your Java solution below
// DO NOT write main() function
int carry = 0;
ListNode result = null, current = null;
while(l1 != null || l2 != null || carry > 0) {
int currentDigit = carry;
if(l1 != null) {
currentDigit += l1.val;
l1 = l1.next;
}
if(l2 != null) {
currentDigit += l2.val;
l2 = l2.next;
}
ListNode newNode = new ListNode(currentDigit % 10);
carry = currentDigit / 10;
if(current == null) {
result = newNode;
} else {
current.next = newNode;
}
current = newNode;
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment