function substractBigNumber(str1, str2) {
const len1 = str1.length
const len2 = str2.length
const maxLength = Math.max(len1, len2)
const arr1 = str1.padStart(maxLength, 0).split('').map((item) => Number(item))
const arr2 = str2.padStart(maxLength, 0).split('').map((item) => Number(item))
// 是否接位
let flag = 0
// 是否交换字符串顺序,减法 区分大数减小数,小数减大数
let change = false
let num1 = arr1[0]
let num2 = arr2[0]
if (num1 < num2) {
change = true
}
let result = ''
for (let i = maxLength - 1; i >= 0; i--) {
let tempRes;
// flag是负数,所以需要+ flag,如果是正数就需要减去
if (change) {
tempRes = arr2[i] - arr1[i] + flag
} else {
tempRes = arr1[i] - arr2[i] + flag
}
if (tempRes < 0) {
flag = -1
// 借位
tempRes = 10 + tempRes
} else {
flag = 0
}
result = `${tempRes}${result}`
}
// 如果都是0000 需要保留最后一个0
result = result.replace(/^0+/, '') || '0'
// 如果交换了位置,代表小数减去大数,需要加上负号
if (change) {
result = `-${result}`
}
return result
}
const str1 = '24300'
const str2 = '2322230'
const result = substractBigNumber(str1, str2)
console.log('计算的结果', result)