导读
机试题,两个字符串相加,好的解法我在沸点中看到过,还研究了下,结果忘了。。。
https://codepen.io/xiaodun/pen/dBWByw
image笨重的实现
机试的时候比下面的更长,因为要兼容IE8!
function strNumAddAble(argNum1 = "", argNum2 = "") {
if (argNum1.length < argNum2.length) {
[argNum1, argNum2] = [argNum2, argNum1];
}
//在前面补0 保证两个字符串长度一致
argNum2 = argNum2.padStart(argNum1.length, "0");
//进位
let addNum = 0;
//存储每次计算的结果
let list = [];
for (let i = argNum1.length - 1; i >= 0; i--) {
let one = argNum1[i];
let two = argNum2[i];
let result = +one + +two + addNum;
addNum = (result / 10) | 0;
let item = result % 10;
list.unshift(item);
}
//循环本省不能处理99 + 1的情况
if (addNum) {
list.unshift("1");
}
return list.join("");
}
console.log(strNumAddAble("10", "2"));
console.log(strNumAddAble("1128", "2"));
console.log(strNumAddAble("939", "1"));
上述的很多逻辑用在处理argNum1,argNum2的长度上,进位的原因,还要再for循环外面处理一下。
好的实现
展现了数组的强大以及while循环的优势
function strNumAddAble(argNum1 = "", argNum2 = "") {
let num1List = [...argNum1],
num2List = [...argNum2];
let isCarry = false;
let result = "";
while (num1List.length || num2List.length || isCarry) {
let item = ~~num2List.pop() + ~~num1List.pop() + isCarry;
result = (item % 10) + result;
isCarry = item > 9;
}
return result;
}
console.log(strNumAddAble("0", "2"));
console.log(strNumAddAble("1128", "2"));
console.log(strNumAddAble("999", "1"));
~~undefined
全等于0
网友评论