【问题标题】:How to add two arrays values of same index and create new array in javascript如何添加相同索引的两个数组值并在javascript中创建新数组
【发布时间】:2023-02-08 20:13:01
【问题描述】:

给定两个非空链表,代表两个非负整数。数字以相反的顺序存储,并且它们的每个节点都包含一个数字。将这两个数字相加并将总和作为链表返回。

您可以假设这两个数字不包含任何前导零,除了数字 0 本身。

Input: l1 = [2,4,3], l2 = [5,6,4] Output: [7,0,8] Explanation: 342 + 465 = 807

【问题讨论】:

标签: javascript arrays


【解决方案1】:

这可以是一种解决方案。

let l1 = [2,4,3];
let l2 = [5,6,4];
let len1 = 0;
let len2 = 0;
let result = [];

let sum = l1.reduce((a, b) => {
    a = a + b * Math.pow(10, len1);
    len1++;
    return a;
  }, 0) + 
  l2.reduce((a, b) => {
    a = a + b * Math.pow(10, len2);
    len2++;
    return a;
   }, 0)
  
 while(sum>0)
 {
  result.push(sum % 10);
  sum = parseInt(sum / 10)
 }
console.log(result)

【讨论】:

    猜你喜欢
    • 2018-09-02
    • 1970-01-01
    • 2021-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多