算法-大数相加
面试中的第一个版本
问题比较多
- 忘记i— j—
- 思路方向对了 但是实现细节不对;太过于绕了,其实可以直接挨着进行加就好了 如果是undefined那就用0来兜底
- 语法比较啰嗦
- Number应该用到每个的上面
亮点
- 双指针大体思路正确
- while循环正确 但实现不对
- unshift和从尾部倒着累加正确
function bigInt(a,b) {
let aArr = [...a]
let bArr = [...b]
let result = []
let tmp = 0
let i = aArr.length - 1
let j = bArr.length - 1
while (aArr.length && bArr.length) {
const isGreaterThan10 = Number(aArr[i] + bArr[j] + tmp) > 10
if (isGreaterThan10) {
tmp = '1'
} else {
tmp = '0'
}
result.unshift(isGreaterThan10 ? aArr[i] + bArr[j] - 10 : aArr[i] + bArr[j])
}
let left = []
if (aArr.length > 0) {
left = aArr
} else if (bArr.length > 0) {
left = bArr
}
result = [...left, ...result]
return result.join('')
}
console.log(bigInt('12345678901234567890', '98765432109876543211110'));
下来后自己实现的版本
var addStrings = function(a, b) {
let aArr = [...a].reverse()
let bArr = [...b].reverse()
const maxLen = Math.max(aArr.length, bArr.length)
let tmp = 0
let result = []
for (let i = 0; i < maxLen; i++) {
const total = (Number(aArr[i]) || 0) + (Number(bArr[i]) || 0) + tmp;
tmp = Math.floor(total / 10)
result.unshift(total % 10)
}
if (tmp > 0) {
result.unshift(1)
}
return result.join('')
};
官方题解
https://leetcode.cn/problems/add-strings/description/
主要是用到了双指针
var addStrings = function(num1, num2) {
let i = num1.length - 1, j = num2.length - 1, add = 0;
const ans = [];
while (i >= 0 || j >= 0 || add != 0) {
const x = i >= 0 ? num1.charAt(i) - '0' : 0;
const y = j >= 0 ? num2.charAt(j) - '0' : 0;
const result = x + y + add;
ans.push(result % 10);
add = Math.floor(result / 10);
i -= 1;
j -= 1;
}
return ans.reverse().join('');
};
Tags: