1. 实现两个字符串相加(不能直接转成数字使用加法运算,因为js精度规定不能超出一定长度)
现场写法完善:
function addStr(a, b) {let res = ''let j = 0const add = (x, y) => {let numif (x + y >= 10) {num = x + y + j - 10j = 1}else{num = x + y + jj = 0}res = res + num.toString()}let a1 = a.split('').reverse()let b1 = b.split('').reverse()let len = a1.length > b1.length ? a1.length : b1.lengthfor (let i = 0; i < len; i++) {let constrastBig = a1.length > b1.length ? 'a' : 'b'let x,yif(constrastBig === 'a'){x = Number(a1[i])y = i > b1.length - 1 ? 0 : Number(b1[i])}else{y = Number(b1[i])x = i > a1.length - 1 ? 0 : Number(a1[i]) }add(x, y)}return res.split('').reverse().join('')
}var x = '123456';
var y = '789';
var z = addStr(x, y);//’124245‘
console.log('z:',z)
var x = '121310987654321';
var y = '2019181716151413121110987654321';
var z = addStr(x, y);//’124245‘
console.log('z:',z)
详见力扣两数相加【使用链表】:https://leetcode.cn/problems/add-two-numbers/