之间在某次面试过程中遇到的,现在做一下记录
function towBigSum(str1, str2) {
// 求两个字符串最大的长度
const maxLen = Math.max(str1.length, str2.length);
// 在字符串头部用0补齐到最大长度
num1_str = str1.padStart(maxLen, '0');
num2_str = str2.padStart(maxLen, '0');
console.log([num1_str, num2_str]);
// 存储进位值的哈希对象
const dp = [];
let resArr = [];
// 循环2个字符串,将对应位置上的数字相加
for(let i=maxLen -1; i >=0; i--){
const index = maxLen - i - 1;
// 对应的字符转为数字相加相加
const plus = parseInt(num1_str.charAt(i), 10) + parseInt(num2_str.charAt(i), 10) + (dp[index] || 0);
console.log(plus);
// resArr的下标
// 相加后的进位值存储在dp哈希表
dp[index+1] = plus > 9 ? 1: 0;
console.log(dp);
resArr[index] = plus < 10 ? plus : plus - 10;
}
if (dp[dp.length -1] > 0 ) {
resArr.push(dp[dp.length - 1]);
}
// 倒置结果集
resArr = resArr.reverse();
// 返回结果集字符串
return resArr.join('');
}
// 测试
console.log(towBigSum('999', '1'));
// 最后返回
// 1000