实现大数相加代码


/**
 * 
 * @param {*} str1 字符串
 * @param {*} str2 字符串
 * @returns 
 */
function addBigNumber(str1, str2) {
    const length1 = str1.length;
    const length2 = str2.length
    const length = Math.max(length1, length2)
    const arr1 = str1.padStart(length, 0).split('').map((item) => Number(item))
    const arr2 = str2.padStart(length, 0).split('').map((item) => Number(item))
    let res = ''
    let flag = 0
    for(let i = length - 1; i >= 0; i--) {
        let result = arr1[i] + arr2[i] + flag
        flag = Math.floor(result / 10)
        res = `${result % 10}` + res
    }
    if (flag) {
        res = `${flag}` + res
    }
    return res
}
const str1 = '111112'
const str2 = '33232'
const result = addBigNumber(str1, str2)
console.log('结果', result)

你可能感兴趣的:(前端,javascript,开发语言)