Adding numbers represented by string without complete conversion in JavaScript


We are required to write a JavaScript function that takes in two strings, str1 and str2 that represents two numbers.

Without converting the whole strings to respective numbers, our function should calculate the sum of those two string numbers and return the result as a string.

For example −

If the two strings are −

const str1 = '234';
const str2 = '129';

Then the output should be 363.−

Example

Following is the code −

const str1 = '234';
const str2 = '129';
const addStringNumbers = (str1, str2) => {
   let ind1 = str1.length - 1,
   ind2 = str2.length - 1,
   res = "",
   carry = 0;
   while(ind1 >= 0 || ind2 >= 0 || carry) {
      const val1 = str1[ind1] || 0;
      const val2 = str2[ind2] || 0;
      let sum = +val1 + +val2 + carry;
      carry = sum > 9 ? 1 : 0;
      res = sum % 10 + res;
      ind1--;
      ind2--;
   };
   return res;
};
console.log(addStringNumbers(str1, str2));

Output

Following is the console output −

363

Updated on: 20-Jan-2021

654 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements