Last active
August 29, 2015 14:02
-
-
Save SleimanJneidi/2440466cd862292dde14 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) { | |
long number1 = Long.parseLong(getNumber(l1, "")); | |
long number2 = Long.parseLong(getNumber(l2, "")); | |
long sum = number1 + number2; | |
ListNode result = fromString(String.valueOf(sum)); | |
return result; | |
} | |
ListNode fromString(String num) { | |
int size = num.length(); | |
ListNode head = new ListNode(Character.getNumericValue(num.charAt((size - 1)))); | |
ListNode current = head; | |
for (int i = size - 2; i >= 0; i--) { | |
current.next = new ListNode(Character.getNumericValue(num.charAt(i))); | |
current = current.next; | |
} | |
return head; | |
} | |
String getNumber(ListNode head, String num) { | |
if (head == null) { | |
return new StringBuilder(num).reverse().toString(); | |
} else { | |
num += "" + head.val; | |
return getNumber(head.next, num); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment