I'm given two non-empty linked lists representing two non-negative integers. Digits are stored in reverse order and each of nodes contain a single digit. The task is adding two numbers and return it as a linked list.
- Input:
(2 -> 4 -> 3) + (5 -> 6 -> 4) - Output:
7 -> 0 -> 8 - Explanation:
342 + 465 = 807
There are several solutions for this problem. I'm trying to solve it by converting linked-list formed digits into numbers. I already did convert the lists to numbers but my problem starts here. You are given a linked-list definition and you can not break it. You don't have a default(empty) constructor in this definition. I am not able to reverse my integer sum into linked-list form yet. Here is my code:
public class ListNode { //given linked -list definition. Should not be manipulated.
int val;
ListNode next;
ListNode(int x) { val = x; }
}
import java.util.*;
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int num1 = getNumber(l1);
int num2 = getNumber(l2);
int sum = num1 + num2;
return ?? //some how I should return a LinkedList where my sum is converted into it
}
//getNumber converts given linked-lists into integers
public int getNumber(ListNode head) {
ListNode tmp = head;
int number = 0;
int pass = 0;
while(tmp != null) {
number += tmp.val * Math.pow(10, pass) ;
tmp = tmp.next;
pass++;
}
return number;
}