
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Adding Numbers Represented by String 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
Advertisements