The problem I am trying to solve is a LeetCode problem, but I am stuck https://leetcode.com/problems/add-two-numbers/
I have tried the following
import java.util.*;
class Solution {
private ListNode l = new ListNode(0);
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int pow = 0;
int counter = 0;
int sum1 = 0;
int sum2 = 0;
while(l1 != null && l2 != null)
{
sum1 = sum1 + ((int) (l1.val * (Math.pow(10,pow))));
sum2 = sum2 + ((int) (l2.val * (Math.pow(10,pow))));
pow++;
l1 = l1.next;
l2 = l2.next;
}
pow = pow - 1;
int final_sum = sum1 + sum2;
String number = String.valueOf(final_sum);
char[] digits = number.toCharArray();
l = l.next;
ListNode x = new ListNode();
x.val = (digits[2] - '0');
l= x;
addElement(digits[1] - '0');
addElement(digits[0] - '0');
return l;
}
public void addElement(int number)
{
ListNode x = new ListNode();
x.val = number;
l.next = x;
}
}
However, I noticed that this just replaces the last given value of ListNode x and does not add on to ListNode l. I am first trying to make it work with one instance of a ListNode without creating multiple "ListNode x = new ListNode()" with different variable names.
At the moment it is just returning [7,8] when given [2,4,3] and [5,6,4] when it should be returning [7,0,8]. Any hints or advice would help.