给你两个 非空 的链表,表示两个非负的整数。它们每位数字都是按照 逆序 的方式存储的,并且每个节点只能存储 一位 数字。
请你将两个数相加,并以相同形式返回一个表示和的链表。
你可以假设除了数字 0 之外,这两个数都不会以 0 开头。
示例 1:
输入:l1 = [2,4,3], l2 = [5,6,4]
输出:[7,0,8]
解释:342 + 465 = 807.
示例 2:
输入:l1 = [0], l2 = [0]
输出:[0]
示例 3:
输入:l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
输出:[8,9,9,9,0,0,0,1]
实现
/**https://leetcode-cn.com/problems/add-two-numbers/
*
* @Author anyao
* @DateTime 2021-04-17
* @param {[array]} l1 [数组1]
* @param {[array]} l2 [数组2]
* @return {[array]} [结果数组]
*/
const getArr = (l1, l2) => {
let xL = Math.max(l1.length, l2.length);
let tem = 0;
let arr = [];
for (let i = 0, g, k; g = l1[i] || 0, k = l2[i] || 0, cur = g + k + tem, i < xL; i++) arr.push(cur % 10), tem = parseInt(cur / 10);
tem > 0 && (arr = [...arr, ...Array.from([...tem.toString()], a => Number(a))]);
return arr;
}
console.log(getArr([2, 4, 3], [5, 6, 4]));
console.log(getArr([0], [0]));
console.log(getArr([9, 9, 9, 9, 9, 9, 9], [9, 9, 9, 9]));
console.log(getArr([2, 4, 5], [1, 3, 6]));