两个长整数字符串求和(不允许使用ES6+), 面试手撸代码遇到到这个问题
1. 实现方式第一种
function fillZero (num, len) {
let str = num.toString();
if (str.length < len) {
str = '0'.repeat(len - str.length) + str;
}
return str;
}
function handlerCarry (num1, num2) {
let arr = []
for (let i = 0; i < num1.length; i++) {
arr.push(Number(num1[i]) + Number(num2[i]))
}
arr = arr.reverse()
arr.forEach((item, index) => {
if (item >= 10) {
arr[index] = item - 10
arr[index + 1] = arr[index + 1] ? arr[index + 1] + 1 : 1
}
})
return arr.reverse().join('')
}
function longIntStrSum (num1, num2) {
let str = ''
let len1 = num1.length;
let len2 = num2.length;
if (len1 < len2) {
num1 = fillZero(num1, len2)
} else if (len1 > len2) {
num2 = fillZero(num2, len1)
}
str = handlerCarry(num1, num2)
return str
}
let num1 = '123412412'
let num2 = '967354215'
console.log(longIntStrSum(num1, num2))
2. 借鉴他人的代码实现两个长整数字符串相加
function sumStrings (a, b) {
var result = [], count = 0;
if (a.length < b.length) b = [a, a = b][0];
b = Array(a.length - b.length + 1).join('0') + b;
var arrA = a.split('');
var arrB = b.split('');
for (var j = 0; j < a.length; j++) {
var temp = (Number(arrA.pop()) + Number(arrB.pop())) + count;
temp >= 10 ? [temp, count] = [temp - 10, 1] : count = 0;
result.push(temp);
}
result.push(count);
return result.reverse().join('').replace(/^0+/, '');
}
let sum = sumStrings('1234', '456789')
console.log(sum)