-
-
Save nhtzr/50677c03ada41bb69e3a61f0b5539a78 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; } | |
* } | |
*/ | |
class Solution { | |
public ListNode addTwoNumbers(ListNode l1, ListNode l2) { | |
return recursiveFunction(l1, l2, new ListNode(0), 0); | |
} | |
public ListNode recursiveFunction(ListNode l1, ListNode l2, ListNode result, int valorEx){ | |
if(l1 == null && l2 == null){ | |
result.val = (valorEx != 0) ? valorEx : result.val | |
return result; | |
} | |
// == extractInputs(l, r) | |
final int summandLeftCurrDigit = ln1 == null ? 0 : ln1.val; | |
final int summandRightCurrDigit = ln2 == null ? 0 : ln2.val; | |
// == doSum(l, r): | |
// get actual sum from input lists & carry over from last iter | |
// A sum (x + y) has to summands (x & y) with x being the left summand and right being the second | |
final int sumWCarry = inputLeftCurrDigit + inputRightCurrDigit + valorEx; | |
// == extractCarryoverCurrDigit(sumWCarry): | |
// transforn the raw sum into the values expected by new node | |
final int newCarry; | |
final int currDigit; | |
if(sumWCarry >= 10){ | |
currDigit = sumWCarry % 10 | |
newCarry = (sumWCarry - currDigit) / 10; | |
} else { | |
currDigit = sumWCarry; | |
newCarry = 0; | |
} | |
// == buildNewNode(currDigit, carryOver) | |
// Save curr digit, and prepare for next iteration w/ carry over | |
result.val = currDigit; | |
result.next = buildNext(ln1, ln2, newCarry, result); | |
return result; | |
} | |
private ListNode buildNext(ln1, ln2, newCarry, result) { | |
// result is an output parameter | |
if(ln1 == null && ln2 == null && newCarry != 0) { | |
return new ListNode(newCarry); | |
} | |
if(ln1 != null && ln2 != null) { | |
if (ln1.next == null && | |
ln2.next == null && | |
newCarry == 0) { | |
return null; | |
} | |
return recursiveFunction(ln1.next, ln2.next, new ListNode(0), valorEx); | |
} | |
if(ln1 != null && | |
ln2 == null){ | |
if(ln1.next == null && | |
newCarry == 0) { | |
return null; | |
} | |
return recursiveFunction(ln1.next, null, new ListNode(0), newCarry); | |
} | |
if(ln1 == null && | |
ln2 != null){ | |
if(ln2.next == null && | |
valorEx== 0) { | |
returnnull ; | |
} | |
return = recursiveFunction(ln2.next, null, new ListNode(0), valorEx); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment