题解 | #大数加法#
大数加法
http://www.nowcoder.com/practice/11ae12e8c6fe48f883cad618c2e81475
function solve( s , t ) {
let sum = "";
let i = s.length - 1, j = t.length - 1;
let carry = 0;
while(i >= 0 || j >= 0){
//这里采用的是取反运算符,当s或者t角标越界时,结果是undefined,~~undefined = 0
// +undefined = NaN, parseInt(undefined) = NaN
let temp = ~~s[i] + ~~t[j] + carry;
if(temp >= 10){
temp %= 10;
carry = 1;
}else{
carry = 0; //需要把carry置为0,不然会影响后面的值
}
sum = temp + sum;
i--;
j--;
}
if(carry == 1) sum = carry + sum;
return sum
}
module.exports = { solve : solve };