DEV Community

Cover image for Given two non-negative integers, num1 and num2 represented as string, return the sum of num1 and num2 as a string.
chandra penugonda
chandra penugonda

Posted on • Updated on

Given two non-negative integers, num1 and num2 represented as string, return the sum of num1 and num2 as a string.

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"
Enter fullscreen mode Exit fullscreen mode

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"));

Enter fullscreen mode Exit fullscreen mode

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

Top comments (0)