Problem Description
Given two non-negative integers represented as strings, num1 and num2, return the sum of num1 and num2 as a string. The solution must simulate the addition process without using any built-in libraries to handle large integers or directly converting the strings to integers.
Key Insights
- Process the input strings from the least significant digit (rightmost) to the most significant (leftmost).
- Maintain a carry for sums exceeding a single digit.
- Use a loop until all digits and any remaining carry have been processed.
- Append the resulting digits (in reverse order) and then reverse the final string to obtain the correct result.
- The approach simulates elementary addition as done by hand.
Space and Time Complexity
Time Complexity: O(max(n, m)) where n and m are the lengths of num1 and num2. Space Complexity: O(max(n, m)) for storing the result.
Solution
The solution uses two pointers that start at the end of each string to simulate digit-by-digit addition. At each step, digits from both strings are added along with the carry from the previous addition. The resulting digit is computed using modulo operation and the carry is updated using integer division. Each computed digit is then appended to a result list. Finally, the list is reversed and joined to form the final result string.