Sum Strings as Numbers
xiqe opened this issue · comments
Jerry Liang commented
Sum Strings as Numbers
Given the string representations of two integers, return the string representation of the sum of those integers.
For example:
sumStrings('1','2') // => '3'
A string representation of an integer will contain no characters besides the ten numerals "0" to "9".
replay
function sumStrings(a,b) {
// 设置var,记录进位,设置连续0的标识位
let [result,empty,zero] = [[],0,0];
// 获取最大的字符串长度
let max = Math.max(a.length,b.length);
for(let i=0;i<max;i++){
let A = a.length - i - 1<0 ? 0 : Number(a[a.length - i - 1]);
let B = b.length - i - 1<0 ? 0 : Number(b[b.length - i - 1]);
let r = A + B + empty;
zero = r == 0?max-i:0;
if(i == max-1){
result.unshift(r);
} else {
if(r<10){
empty = 0;
result.unshift(r);
} else {
empty = 1;
result.unshift(r-10);
}
}
}
return result.join('').substring(zero);
}