Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Add number strings without using conversion library methods in JavaScript
We are required to write a JavaScript program that adds two numbers represented as strings, without using any conversion library or built-in methods. For example, If the input number strings are '11' and '23', the output should be '34'.
In JavaScript, a number is considered a string-represented number when the number is enclosed in single quotes ('number') or double quotes ("number"). For example: '123' or "456". If you use the typeof operator on such values, it will return the type as 'string'.
Here are a few input and output scenarios that provide a better understanding of the given problem:
Scenario 1
<b>Input:</b> str1 = '123', str2 = '456' <b>Output:</b> '579' <b>Explanation:</b> We are adding two numbers strings '123' and '456' digit by digit from right to left, just like regular math addition: 1 2 3 + 4 5 6 ------- 5 7 9 3 + 6 = 9 (no carry) 2 + 5 = 7 (no carry) 1 + 4 = 5 (no carry)
Scenario 2
<b>Input:</b> str1 = '999', str2 = '1' <b>Output:</b> '1000' <b>Explanation:</b> We are adding two numbers strings '999' and '1' digit by digit from right to left, just like regular math addition: 9 9 9 + 1 ------- 1 0 0 0 9 + 1 = 10 (write 0, carry 1) 9 + carry = 10 (write 0, carry 1) 9 + carry = 10 (write 0, carry 1) Final carry = 1
Algorithm
The following algorithm is implemented in the JavaScript program to solve the given problem:
- Step 1: Initialize variables to traverse both strings from right to left (least significant digit first).
- Step 2: Initialize a carry variable with value 0 and an empty result string.
- Step 3: Loop through each digit from right to left: Get digits from both strings (or 0 if string ended), add them with carry.
- Step 4: If the sum is greater than 9, store (sum % 10) and set carry = 1. Otherwise, store the sum and set carry = 0.
- Step 5: Prepend each digit to the result string. If carry remains after the loop, prepend it to the result.
- Step 6: Return the final sum string.
Example
The following JavaScript program uses the above algorithm to solve the given problem. It adds two numbers represented as strings without converting them using any library methods:
function addStrings(num1, num2) {
let i = num1.length - 1;
let j = num2.length - 1;
let carry = 0;
let result = '';
// Process digits from right to left
while (i >= 0 || j >= 0 || carry > 0) {
// Get digit from each string (or 0 if string ended)
let digit1 = i >= 0 ? num1[i].charCodeAt(0) - 48 : 0; // ASCII '0' = 48
let digit2 = j >= 0 ? num2[j].charCodeAt(0) - 48 : 0;
// Calculate sum
let sum = digit1 + digit2 + carry;
// Extract digit and carry
let currentDigit = sum % 10;
carry = Math.floor(sum / 10);
// Prepend digit to result
result = currentDigit + result;
i--;
j--;
}
return result;
}
// Test examples
console.log("Example 1:");
console.log("'123' + '456' =", addStrings('123', '456'));
console.log("\nExample 2:");
console.log("'999' + '1' =", addStrings('999', '1'));
console.log("\nExample 3:");
console.log("'11' + '23' =", addStrings('11', '23'));
Example 1: '123' + '456' = 579 Example 2: '999' + '1' = 1000 Example 3: '11' + '23' = 34
Key Points
- We use
charCodeAt(0) - 48to convert character digits to numbers without using parseInt() - ASCII value of '0' is 48, so '0'.charCodeAt(0) - 48 = 0, '1'.charCodeAt(0) - 48 = 1, etc.
- We process digits from right to left, handling carry just like manual addition
- The algorithm works for strings of any length, including edge cases with different lengths
- Time complexity is O(max(m,n)) where m and n are the lengths of input strings
Alternative Approach Using String Manipulation
Here's another implementation that avoids charCodeAt() by using a digit mapping:
function addStringsAlternative(num1, num2) {
const digitMap = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9};
let i = num1.length - 1;
let j = num2.length - 1;
let carry = 0;
let result = '';
while (i >= 0 || j >= 0 || carry > 0) {
let digit1 = i >= 0 ? digitMap[num1[i]] : 0;
let digit2 = j >= 0 ? digitMap[num2[j]] : 0;
let sum = digit1 + digit2 + carry;
result = (sum % 10) + result;
carry = Math.floor(sum / 10);
i--;
j--;
}
return result;
}
console.log("Alternative method: '999' + '999' =", addStringsAlternative('999', '999'));
Alternative method: '999' + '999' = 1998
Conclusion
Adding number strings without conversion libraries requires implementing manual addition logic with carry handling. The key is processing digits from right to left and managing carries properly, just like mathematical addition on paper.
