//5.06 -21
function plus(str1, str2) {
let len1 = str1.length;
let len2 = str2.length;
if (len1 > len2) {
str2 = str2.padStart(len1, "0");
} else if (len1 < len2) {
str1 = str1.padStart(len2, "0");
}
// console.log(str1, str2);
let j = 0,
r = "";
for (let i = Math.max(len1, len2) - 1; i >= 0; i--) {
let sum = Number(str1[i]) + Number(str2[i]) + j;
j = Math.floor(sum / 10);
r += sum % 10;
}
if (j > 0) {
r += j;
}
console.log(r.split("").reverse().join(""));
}
plus("12", "1208");
//8:13 -29 -35 -43
function multiplication(str1, str2) {
let num = 0,
tp = [],
n = 0;
for (let j = str2.length - 1; j >= 0; j--) {
tp = [];
for (let i = str1.length - 1; i >= 0; i--) {
let sum = str1[i] * str2[j] + num;
num = Math.floor(sum / 10);
let k = sum % 10;
tp.unshift(k);
}
let c = 0;
for (let i = tp.length - 1; i >= 0; i--) {
c += tp[i] * Math.pow(10, tp.length - 1 - i);
}
n += c * Math.pow(10, str2.length - j - 1);
}
console.log(n);
return n;
}
multiplication("123", "123");
大数加法和乘法
最新推荐文章于 2024-11-10 22:45:39 发布