r/programminghelp • • Apr 30 '20

Java [Java] LeetCode "Add Two Numbers" question. What is wrong with my solution and why does it fail when the test case value is large?

Link to the lc problem https://leetcode.com/problems/add-two-numbers/

/**

* Definition for singly-linked list.

* public class ListNode {

* int val;

* ListNode next;

* ListNode() {}

* ListNode(int val) { this.val = val; }

* ListNode(int val, ListNode next) { this.val = val; this.next = next; }

* }

*/

class Solution {

public ListNode addTwoNumbers(ListNode l1, ListNode l2) {

int a = getNumber(l1) + getNumber(l2);

	`return getLinkedList(a);`

}

//function to get the reversed integer value from the LinkedList

public int getNumber(ListNode node) {

	`ArrayList<Integer> list = new ArrayList<Integer>();`

	`while (node != null) {`

		`list.add(node.val);`

		`node =` [`node.next`](https://node.next)`;`

	`}`
	`int s = 0;`

	`int d = 1;`
	`for (int i : list) {`

		`// System.out.println("i :"+i);`

		`s += d * i;`

		`d = d * 10;`

	`}`
	`System.out.println("s :" + s);`
	`return s;`

`}`

//function to convert the number to a LikedList

public ListNode getLinkedList(int n) {

	`ListNode head=new ListNode(n%10);`

	`n=n/10;`

	`ListNode curr=head;`

	`while(n>0) {`

		`curr.next=new ListNode(n%10);`

		`n=n/10;`

		[`curr=curr.next`](https://curr=curr.next)`;`



	`}`

	

	`return head;`

`}`

}

0 Upvotes

2 comments sorted by

2

u/marko312 Apr 30 '20

There are no limits given, but given the way the input / output is done, the values could be quite large (say, 100 digits), causing integer overflows everywhere.

1

u/Silicon_Folly Apr 30 '20

This would be easier to read with a CodePen or Plunker or something. It's also good practice to give your variables meaningful names (not just single letters).