- 实现整数相加
- 实现浮点数相加
- 实现多数相加
代码已经通过 LeetCode 检测通过,感觉还是有很多可以优化的空间,还烦请留言赐教,谢谢。
function bigNumberAddition() {
function cutNumberByDot(_n) {
const n = String(_n);
return n.split('.');
}
function addition(n1, n2) {
const [n1_integer, n1_float] = cutNumberByDot(n1);
const [n2_integer, n2_float] = cutNumberByDot(n2);
let plusOne = 0;
let float = '';
if (n1_float && n2_float) {
let shortNumber = n1_float.length > n2_float.length ? n2_float : n1_float;
const longNumber = n1_float.length < n2_float.length ? n2_float : n1_float;
for (let i = 0; i < longNumber.length; i++) {
if (!shortNumber[i]) {
shortNumber += '0';
}
}
float = integerAddition(shortNumber, longNumber);
if (float.length > longNumber.length) {
plusOne = 1;
float = float.substr(1);
}
} else if (n1_float || n2_float) {
float = (n1_float || n2_float);
}
let integer = integerAddition(n1_integer, n2_integer, plusOne);
let ret;
if (n1_float || n2_float) {
ret = integer + '.' + float;
} else {
ret = integer;
}
return ret;
}
function integerAddition() {
// 记得给参数转字符串
const args = [...arguments].map((arg) => typeof (arg) !== "string" ? String(arg) : arg);
return args.reduce((s1 = '0', s2 = '0') => {
let s1index = s1.length - 1;
let s2index = s2.length - 1;
let plusOne = 0;
let ret = '';
while (s1index >= 0 || s2index >= 0) {
const sum = +(s1[s1index] ?? 0) + +(s2[s2index] ?? 0) + plusOne;
if (sum >= 10) {
ret = sum % 10 + ret;
plusOne = 1;
} else {
ret = sum + ret;
plusOne = 0;
}
s1index--;
s2index--;
}
// 记得最后还要判断一下是否还需要再加一位 1 在结果的前面
return plusOne ? plusOne + ret : ret;
})
}
const args = [...arguments];
return args.reduce((prev, next) => addition(prev, next));
}