Created
April 29, 2020 06:42
-
-
Save adnan-SM/9bc6674c6ab3e5df6f7ee588ade946d4 to your computer and use it in GitHub Desktop.
Add Numbers
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
class Solution { | |
public ListNode addTwoNumbers(ListNode l1, ListNode l2) { | |
return addNumbersHelper(l1, l2, 0); | |
} | |
public ListNode addNumbersHelper(ListNode l1, ListNode l2, int carry) { | |
if(l1 == null && l2 == null && carry == 0) { | |
return null; | |
} | |
int value = carry; | |
if(l1 != null) { | |
value += l1.val; | |
} | |
if(l2 != null) { | |
value += l2.val; | |
} | |
ListNode result = new ListNode(value%10); | |
if(l1 != null || l2 != null) { | |
ListNode more = addNumbersHelper(l1 == null? null: l1.next,l2 == null? null: l2.next, value >= 10? 1:0); | |
result.next = more; | |
} | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment