HackerRank A Very Big Sum | JS Solution

HackerRank A Very Big Sum | JS Solution

1. Problem

Input: Array of numbers

Output: A number

Return a total sum of all of the numbers in the array. Keep in mind that the resulting sum might exceed the maximum range allowed.

2. Edge Cases / Test Cases

let testArr = [1000000001, 1000000002, 1000000003, 1000000004, 1000000005];

3. Data Types / Structures / Big O complexity

Number and array.

4. Pseudo Code

We want to loop over the array and add all numbers inside of it by either using a for loop or .reduce() method that reduces values of an array to a single value.

5. Code

// Solution #1
function aVeryBigSum(arr) {
  const reducer = (accumulator, currentValue) => accumulator + currentValue;
  return arr.reduce(reducer);
}

// Solution #2
function aVeryBigSum(arr) {
  let sum = 0;
  for (let i = 0; i < arr.length; i++) {
    sum += arr[i];
  }
  return sum;
}

Sources:

  1. A Very Big Sum Problem by HackerRank
  2. PEDAC Algorithm Solving Approach by LaunchSchool