
Sponsored
Sponsored
This approach involves reversing both input strings, then iterating through them to sum up each digit, similar to manual addition from the rightmost digit. This technique simplifies handling the carry over during addition.
Time Complexity: O(n), where n is the maximum length of num1 or num2.
Space Complexity: O(n), for the result array.
1function addStrings(num1, num2) {
2 let carry = 0, i = num1.length - 1, j = num2.length - 1;
3 let result = [];
4
5 while (i >= 0 || j >= 0 || carry !== 0) {
6 const x = i >= 0 ? +num1[i] : 0;
7 const y = j >= 0 ? +num2[j] : 0;
8
9 const sum = x + y + carry;
10 result.push(sum % 10);
11 carry = Math.floor(sum / 10);
12
13 i--;
14 j--;
15 }
16
17 return result.reverse().join('');
18}
19
20// Example usage:
21console.log(addStrings("11", "123"));The JavaScript solution uses a dynamic array to accumulate the result of digit sums. By iterating from the last character towards the first, we manage carries and ensure correct digit placement. Reversing and joining the array provides a final string output.
This approach deploys two pointers, initially positioned at the end of each input string. We process each character one by one, moving the pointers from the rightmost end towards the start of each string. This allows us to readily manage the carry as we compute the sum step-by-step.
Time Complexity: O(n), where n is the maximum length of num1 or num2.
Space Complexity: O(n), necessary for the dynamically allocated result string.
1
The Python function addStrings handles addition across variable-length strings via iteration in reverse order, merging carry logic with character processing. Utilization of int type conversion allows precise digit handling, supporting list-based result formation for concise finalization.