Question: A Very Big Sum - - Hacker Rank Problem C++ Calculate and print the sum of the elements in an array, keeping in mind that

A Very Big Sum - - Hacker Rank Problem C++

Calculate and print the sum of the elements in an array, keeping in mind that some of those integers may be quite large.

Function Description Complete the function aVeryBigSum described below to return the sum of all elements of the array.

aVeryBigSum(integer: n, integer: arr_size, integer array: arr)

Parameters: n: array size

arr_size: array size

ar: array of integers to sum

Returns: integer sum of all array elements

Constraints

1 < = N< = 10 0< = A[i]<= 1010

Sample Input 5 1000000001 1000000002 1000000003 1000000004 1000000005

Output Print a single value equal to the sum of the elements in the array. In the above sample, you would print 5000000015.

The solution to this problem can be found on the web, but my point is that usually helpful comments and insightful comments are missing from the source code. Please include your reasoning and logic on your solution.

#include

using namespace std;

vector split_string(string);

/* * Complete the aVeryBigSum function below. */ long aVeryBigSum(int n, vector ar) { /* * Write your code here. */

}

int main() { ofstream fout(getenv("OUTPUT_PATH"));

int n; cin >> n; cin.ignore(numeric_limits::max(), ' ');

string ar_temp_temp; getline(cin, ar_temp_temp);

vector ar_temp = split_string(ar_temp_temp);

vector ar(n);

for (int ar_itr = 0; ar_itr < n; ar_itr++) { long ar_item = stol(ar_temp[ar_itr]);

ar[ar_itr] = ar_item; }

long result = aVeryBigSum(n, ar);

fout << result << " ";

fout.close();

return 0; }

vector split_string(string input_string) { string::iterator new_end = unique(input_string.begin(), input_string.end(), [] (const char &x, const char &y) { return x == y and x == ' '; });

input_string.erase(new_end, input_string.end());

while (input_string[input_string.length() - 1] == ' ') { input_string.pop_back(); }

vector splits; char delimiter = ' ';

size_t i = 0; size_t pos = input_string.find(delimiter);

while (pos != string::npos) { splits.push_back(input_string.substr(i, pos - i));

i = pos + 1; pos = input_string.find(delimiter, i); }

splits.push_back(input_string.substr(i, min(pos, input_string.length()) - i + 1));

return splits; }

Expert Answer

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!