无需 JavaScript 的转换库方法即可添加数字字符串
我们需要编写一个 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP