
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
Add Number Strings Without Using Conversion Library Methods in JavaScript
We are required to write a JavaScript function that takes in two number strings. The function should add the numbers in the string without actually converting them to numbers or using any other conversion library methods.
For example −
If the input strings are −
const str1 = '123'; const str2 = '456';
Then the output should be −
const output = '579';
Example
The code for this will be −
const str1 = '123'; const str2 = '456'; const addStrings = (num1, num2) => { // Let's make sure that num1 is not shorter than num2 if (num1.length < num2.length) { let tmp = num2; num2 = num1; num1 = tmp; } let n1 = num1.length; let n2 = num2.length; let arr = num1.split(''); let carry = 0; let total; for (let i = n1 − 1, j = n2 − 1; i >= 0; i−−, j−−) { let term2 = carry + (j >= 0 ? parseInt(num2[j]) : 0); if (term2) { total = parseInt(num1[i]) + term2; if (total > 9) { arr[i] = (total − 10).toString(); carry = 1; } else { arr[i] = total.toString(); carry = 0; if (j < 0) { break; } } } } return (total > 9 ? '1' + arr.join('') : arr.join('')); }; console.log(addStrings(str1, str2));
Output
And the output in the console will be −
579
Advertisements