Given two non-negative integers, num1 and num2 represented as string, return the sum of num1 and num2 as a string.
chandra penugonda
Posted on July 22, 2023
This problem was asked by Facebook.
Given two non-negative integers, num1 and num2 represented as string, return the sum of num1 and num2 as a string.
Example
function addStrings(num1, num2) {
};
console.log(addStrings('111', '2222')) // "111" + "2222" = "2333"
Notes: You cannot use any built-in BigInteger library
- num1 and num2 consist of only digits.
- num1 and num2 don't have any leading zeros except for the zero itself.
Solution
function addStrings(num1, num2) {
let i = num1.length - 1,
j = num2.length - 1;
let result = "";
let carry = 0;
while (i >= 0 || j >= 0 || carry > 0) {
const n1 = num1[i] ? parseInt(num1[i]) : 0;
const n2 = num2[j] ? parseInt(num2[j]) : 0;
const sum = n1 + n2 + carry;
carry = Math.floor(sum / 10);
result = (sum % 10) + result;
i--;
j--;
}
return result;
}
console.log(addStrings("111", "2222"));
Explanation
- Initialize pointers i and j to the end of the input strings
- Initialize carry to 0
- Loop through and calculate the sum of digits at i and j indices, plus carry
- Update carry and append digit to result
- Decrement i and j
- Return result string
This iterates through the strings digit-by-digit while tracking the carry, building up the result string in reverse order
💖 💪 🙅 🚩
chandra penugonda
Posted on July 22, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
javascript Remove the duplicates in-place such that each unique element appears only once
July 23, 2023