Intuition
Convert both linked lists to integers, add them, then convert the sum back to a linked list.
Explanation
Brute Force
Traverse each list to extract its digits, reconstruct the integer (using the reverse-order representation), add the two integers, then convert the result back to a linked list digit by digit.
This works correctly but requires extracting the full number, which can overflow for very large inputs in some languages (Python handles big integers natively, but Java/C++ would fail for 100-digit numbers).
Time is O(n + m) where n and m are the list lengths. Space is O(max(n, m)) for the output.
Why it's not ideal: while it works in Python, it conceptually misses the point of the digit-by-digit approach and fails in languages with fixed-width integers.
Implementation
import java.math.BigInteger;
class Solution {
static class ListNode {
int val;
ListNode next;
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
BigInteger num1 = toNumber(l1);
BigInteger num2 = toNumber(l2);
BigInteger total = num1.add(num2);
if (total.equals(BigInteger.ZERO)) {
return new ListNode(0);
}
ListNode dummy = new ListNode(0);
ListNode current = dummy;
while (total.compareTo(BigInteger.ZERO) > 0) {
BigInteger[] divMod = total.divideAndRemainder(BigInteger.TEN);
current.next = new ListNode(divMod[1].intValue());
current = current.next;
total = divMod[0];
}
return dummy.next;
}
private BigInteger toNumber(ListNode node) {
BigInteger result = BigInteger.ZERO;
BigInteger power = BigInteger.ONE;
while (node != null) {
result = result.add(BigInteger.valueOf(node.val).multiply(power));
power = power.multiply(BigInteger.TEN);
node = node.next;
}
return result;
}
}