Last active
October 2, 2018 05:48
-
-
Save hsaputra/ea847949eb05b3c1db7adcf152b5c056 to your computer and use it in GitHub Desktop.
Add Two Numbers - https://leetcode.com/problems/add-two-numbers/description/
This file contains hidden or 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; } | |
* } | |
*/ | |
class Solution { | |
public ListNode addTwoNumbers(ListNode l1, ListNode l2) { | |
// Cases" | |
// 1. Same size | |
// 2. Diff length | |
// 3. Either null | |
// 4. No leading zero | |
if (l1 == null || l2 == null) { | |
return null; | |
} | |
ListNode curL1 = l1; | |
ListNode curL2 = l2; | |
final ListNode resultRoot = new ListNode(0); | |
int carry = 0; | |
ListNode curResult = resultRoot; | |
while (curL1 != null || curL2 != null) { | |
int valL1 = curL1 != null ? curL1.val : 0; | |
int valL2 = curL2 != null ? curL2.val : 0; | |
// operations | |
int sum = carry + valL1 + valL2; | |
int reminder = sum % 10; | |
carry = sum / 10; | |
// update result | |
curResult.next = new ListNode(reminder); | |
// Update pointers | |
curL1 = curL1 != null ? curL1.next : null; | |
curL2 = curL2 != null ? curL2.next : null; | |
curResult = curResult.next; | |
} | |
// Check carry | |
if (carry > 0) { | |
curResult.next = new ListNode(carry); | |
} | |
return resultRoot.next; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
OR