2. Add Two Numbers ๐ข
Last updated
Last updated
Difficulty: Medium
- Tags: Linked List
, Math
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
๐น Example 1:
Input:
Output:
Explanation: 342 + 465 = 807.
๐น Example 2:
Input:
Output:
๐น Example 3:
Input:
Output:
The number of nodes in each linked list is in the range [1, 100]
.
0 <= Node.val <= 9
It is guaranteed that the list represents a number that does not have leading zeros.
To solve this problem, we can simulate the addition of the two numbers digit by digit, starting from the least significant digit (the head of each linked list):
Traverse both linked lists simultaneously, adding corresponding digits along with any carry.
If the sum of two digits is 10 or more, store the unit digit of the sum in the result and carry the tens digit to the next iteration.
Once all nodes are processed, if there is any carry left, append it to the result.
Simulate Addition:
We add corresponding digits from both linked lists and handle the carry from the previous step.
Handling Carry:
If the sum of two digits is greater than or equal to 10, we store the unit digit in the result and carry the tens digit over.
Edge Cases:
If one linked list is longer than the other, we treat the missing digits as zero.
If there is a remaining carry after the last node, we append it to the result.
O(n): We traverse both linked lists once, where n
is the length of the longer list.
O(n): The space complexity is O(n) because we are constructing a new linked list of size n
.
You can find the full solution here.