Hacker Rank Problem Solving in PHP - A Very Big Sum

HackerRank Problem Solving - A Very Big Sum

Function Description

Complete the aVeryBigSum function in the editor below. It must return the sum of all array elements.

aVeryBigSum has the following parameter(s):

  • int ar[n]: an array of integers .

Return

  • long: the sum of all array elements

Input Format

The first line of the input consists of an integer n.
The next line contains n space-separated integers contained in the array.

Output Format

Return the integer sum of the elements in the array.

 

Solution in PHP:

<?php

/** Complete the 'aVeryBigSum' function below.
*
* The function is expected to return a LONG_INTEGER.
* The function accepts LONG_INTEGER_ARRAY ar as parameter.
*/

function aVeryBigSum($ar) {
   // Write your code here
   $sum = 0;
   foreach ($ar as $element) {
      $sum += $element;
   }
   return $sum;
}

$fptr = fopen(getenv("OUTPUT_PATH"), "w");

$ar_count = intval(trim(fgets(STDIN)));

$ar_temp = rtrim(fgets(STDIN));

$ar = array_map('intval', preg_split('/ /', $ar_temp, -1, PREG_SPLIT_NO_EMPTY));

$result = aVeryBigSum($ar);

fwrite($fptr, $result . "\n");

fclose($fptr);

 

Press ESC to close