Created
March 23, 2013 21:40
-
-
Save linzhp/5229466 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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