一笔巨款 - Hacker Rank

A very big sum - Hacker Rank

我正在尝试解决 Hacker Rank 上的“A very big sum”挑战:https://www.hackerrank.com/challenges/a-very-big-sum/problem

在那里我必须对给定数组中的所有数字求和,所以我想出了两个解决方案:

第一个解决方案

function aVeryBigSum(ar){
  let sum = 0;
  for(let i = 0; i < ar.length; i++){
     sum += i;
   }
}

第二种解法

function(ar){
 let sum = ar.reduce((accumulator, currentValue) => {
  accumulator + currentValue;
    });
}

但其中 none 有效,我不知道为什么,我在想也许我没有按照 Hacker Rank 的要求编写它,但我不确定

sum += i; 应该是 sum += ar[i];

还有return和

function aVeryBigSum(ar){
  let sum = 0;
  for(let i = 0; i < ar.length; i++){
     sum += ar[i];
  }
  return sum;
}

reducer 函数也应该像

function a(ar){
  let sum = (accumulator, currentValue) => accumulator + currentValue;
  return ar.reduce(sum);
}

在您的第一个解决方案中,您应该为数组建立索引,而不是仅仅将索引相加:

function aVeryBigSum(ar){
  let sum = 0;
  for(let i = 0; i < ar.length; i++){
     sum += ar[i];
  }
  return sum;
}

用reduce对数组求和:

function aVeryBigSum(ar){
  return ar.reduce((a, b) => a + b, 0);
}

此外,请注意您应该在函数中 return 值。 尽管这适用于数字较小的数组,但您应该考虑如果总和达到 very large 会发生什么情况。 (请参阅关于 HackerRank 的 注释 部分。)

你的两个解决方案都不RETURN总和

function aVeryBigSum(ar) {
    let sum = 0;
    ar.forEach(s =>{
    sum += s;
  });
  return sum;
}

示例输入 [1000000001 ,1000000002 ,1000000003, 1000000004, 1000000005]

function aVeryBigSum(ar) {
  let score = 0;

  for(let i =0; i< ar.length;i++) {
    score += parseInt(ar[i].toString().substring(0));
  }

  return score;
}

您需要处理这些 HackerRank 挑战中的所有边缘案例和极端案例。观察评论,这都通过了。

// ** Input **
const input1 = [1000000001, 1000000002, 1000000003, 1000000004, 1000000005]
const input2 = [5555]
const input3 = '10'

// ** Solution **
function aVeryBigSum(ar) {

  // Declare Working Variable
  let sum = ar

  // If Already Integer >> Return as Sum
  if (typeof sum == 'number') {
    return sum
  }

  // If String or Object
  if (typeof sum == 'string' || typeof sum == 'object') {

    // Split String into Array at Space
    if (typeof sum == 'string') { sum = sum.split(' ') }

    // Reduce
    sum = sum.reduce((a,b) => {

      // If Number > Parse as Integer
      (typeof a == 'number' && typeof b == 'number')
      a = parseInt(a)
      b = parseInt(b)

      return a += b
    }, 0)

    // Return Sum
    return sum
  }
}

// ** Testing **
console.log(aVeryBigSum(input1))
console.log(aVeryBigSum(input2))
console.log(aVeryBigSum(input3))