The task is to implement a string subtraction function with all non-negative integers in string.
The boilerplate code
function subtract(num1, num2) {
// your code here
}
First, remove leading zeros from both input strings. If the string is empty, replace with zero.
num1 = num1.replace(/^0+/, '') || '0';
num2 = num2.replace(/^0+/, '') || '0';
If num1 < num2, the function returns 0 because a negative number can't be the result
if (compare(num1, num2) < 0) return "0";
Make num2 the same length as num1 by adding leading zeros to be able to subtract digit by digit from right to left
num2 = num2.padStart(num1.length, '0');
Subtract from right to left, keeping a borrow (0 or 1). The borrow is 0 when the value being subtracted from is greater than the value being subtracted, otherwise it is 1.
let res = '';
let borrow = 0;
for (let i = num1.length - 1; i >= 0; i--) {
let digit1 = +num1[i];
let digit2 = +num2[i] + borrow;
if (digit1 < digit2) {
digit1 += 10;
borrow = 1;
} else {
borrow = 0;
}
res = (digit1 - digit2) + res;
}
return res.replace(/^0+/, '') || '0';
digit1 is the value of num1[i], digit2 is the value of num2[i] + borrow. If digit1 < digit2, add 10 to digit1 and set borrow to 1, otherwise set borrow to 0. Remove the leading zeros from the result.
The final code
function subtract(num1, num2) {
// your code here
num1 = num1.replace(/^0+/, '') || '0';
num2 = num2.replace(/^0+/, '') || '0';
if (compare(num1, num2) < 0) return "0";
let res = '';
let borrow = 0;
num2 = num2.padStart(num1.length, '0');
for (let i = num1.length - 1; i >= 0; i--) {
let digit1 = +num1[i];
let digit2 = +num2[i] + borrow;
if (digit1 < digit2) {
digit1 += 10;
borrow = 1;
} else {
borrow = 0;
}
res = (digit1 - digit2) + res;
}
return res.replace(/^0+/, '') || '0';
}
function compare(a, b) {
if (a.length !== b.length) return a.length - b.length;
return a.localeCompare(b);
}
That's all folks!
Top comments (0)