题解 | #高精度整数加法#
高精度整数加法
http://www.nowcoder.com/practice/49e772ab08994a96980f9618892e55b6
//数字超过了NUMBER.MAX_SAFE_INTEGER,所以这里使用对位相加,写的有点烂,凑活看
let arr = []
let n = 2;
while(line = readline()) {
arr.push(line);
}
for (let i = 0; i<arr.length/n; i++) {
let list = arr.slice(n*i, n*(i+1));
let a = list[0];
let b = list[1];
let long = a.length > b.length ? a : b; // 这里判断长短
let short = long == a ? b : a;
let diffL = long.length - short.length;
let diffS = diffL ? long.substr(0, diffL) : ''; // 获取长的字符串多出的部分
let newLong = long.substring(diffL);
let combineStr = combine(newLong, short, diffS);
print(combineStr)
}
function combine(str1, str2, diffS) {
let arr1 = str1.split('').reverse();
let arr2 = str2.split('').reverse();
let arr3 = new Array(arr1.length + 1).fill(0); // 存储两个等长相加的字符串
for (let i= 0; i<arr1.length; i++) {
let num = arr3[i] + parseInt(arr1[i]) + parseInt(arr2[i]);
if (num >= 10) {
arr3[i + 1] = arr3[i + 1] + 1;
arr3[i] = num - 10;
} else {
arr3[i] = num;
}
}
let lastNum = arr3.pop(); // 判断最高位是1还是0
if (lastNum == 0) {
return diffS + arr3.reverse().join('');
} else {
if (diffS.length) {
let arr = diffS.split('').reverse().map(x => parseInt(x));
arr[0] = arr[0] + 1;
for (let i= 0; i<arr.length; i++) {
if(arr[i] >= 10) {
arr[i + 1] = arr[i + 1] + 1;
arr[i] = arr[i] - 10;
}
}
return arr.reverse().join('') + arr3.reverse().join('');
}
else {
return '1'+ arr3.reverse().join('');
}
}
}