在 JavaScript 中不使用转换库方法添加数字字符串
javascriptweb developmentfront end technologyobject oriented programming
我们需要编写一个接受两个数字字符串的 JavaScript 函数。该函数应该将字符串中的数字相加,而无需实际将它们转换为数字或使用任何其他转换库方法。
例如 −
如果输入字符串是 −
const str1 = '123'; const str2 = '456';
那么输出应该是 −
const output = '579';
示例
其代码为 −
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));
输出
控制台中的输出将是 −
579
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

