The task is to implement a string addition function with all non-negative integers in string.
The boilerplate code:
function add(num1, num2) {
// your code here
}
The addition begins by starting from the end of both strings
let i = num1.length - 1
let j = num.length - 1
When 2 numbers are added, and the result is greater than 10, the first number is carried over to the next number pair
let carry = 0
While there are digits left to be added or numbers that are carried, the addition operation continues
while(i >= 0 || j >= 0 || carry > 0) {
const digit1 = i >= 0 ? Number(num1[i--]) : 0;
const digit2 = j >= 0 ? Number(num2[j--]) : 0;
const sum = digit1 + digit2 + carry;
}
The result for each addition will be the remainder after the first number is carried
result = (sum % 10) + result;
The value of the number carried
carry = Math.floor(sum / 10)
The final code:
function add(num1, num2) {
// your code here
let i = num1.length - 1;
let j = num2.length - 1;
let carry = 0;
let result = '';
while(i >= 0 || j >= 0 || carry > 0) {
const digit1 = i >= 0 ? Number(num1[i--]) : 0;
const digit2 = j >= 0 ? Number(num2[j--]) : 0;
const sum = digit1 + digit2 + carry;
result = (sum % 10) + result;
carry = Math.floor(sum / 10)
}
return result;
}
That's all folks!
Top comments (0)