A very big sum - Hacker Rank

Viewed 9063

I am trying to solve "A very big sum" challenge on Hacker Rank: https://www.hackerrank.com/challenges/a-very-big-sum/problem

In there I have to sum all the numbers in the array given so I came up with two solutions:

First solution

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

Second Solution

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

But none of them work and I don´t know why, I am thiniking maybe I am not writing it as Hacker Rank wants me to but I am not sure

5 Answers

sum += i; should be sum += ar[i];

Also return sum

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

Also reducer function should be like

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

In your first solution, you should index the array instead of just adding up the indexes:

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

To sum the array with reduce:

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

Also, note that you should return values in the functions. Although this works for arrays with small numbers, you should think about what can happen if the sum gets very large. (See the note section on HackerRank.)

both of your solutions do not RETURN the sum

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

You need to handle all edge cases and corner cases on these HackerRank challenges. Observe comments, this passes all.

// ** 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))

sample input [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;
}
Related