|
| 1 | +/** |
| 2 | + * @param {string} num1 First number to be added, represented as string. |
| 3 | + * @param {string} num2 Second number to be added, represented as string. |
| 4 | + * @return {string} String representing sum of num1 and num2. |
| 5 | + * @summary Add Strings {@link https://leetcode.com/problems/add-strings/} |
| 6 | + * @description Given two numbers represented as strings, return sum of them. No built-in library for handling big numbers allowed. |
| 7 | + * Space O(n) - Where n is Math.max(num1.length, num2.length). |
| 8 | + * Time O(n) - Where n is Math.max(num1.length, num2.length). |
| 9 | + */ |
| 10 | +const addStrings = (num1, num2) => { |
| 11 | + const answer = []; |
| 12 | + |
| 13 | + let carryOver = 0; |
| 14 | + let index1 = num1.length - 1; |
| 15 | + let index2 = num2.length - 1; |
| 16 | + |
| 17 | + while (index1 >= 0 || index2 >= 0) { |
| 18 | + const n1 = index1 >= 0 ? +num1[index1] : 0; |
| 19 | + const n2 = index2 >= 0 ? +num2[index2] : 0; |
| 20 | + |
| 21 | + const sum = n1 + n2 + carryOver; |
| 22 | + |
| 23 | + carryOver = sum > 9 ? 1 : 0; |
| 24 | + answer.unshift(sum % 10); |
| 25 | + |
| 26 | + index1--; |
| 27 | + index2--; |
| 28 | + } |
| 29 | + |
| 30 | + if (carryOver) answer.unshift(1); |
| 31 | + |
| 32 | + return answer.join(''); |
| 33 | +}; |
0 commit comments