Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

A Very Big Sum - - Hacker Rank Calculate and print the sum of the elements in an array, keeping in mind that some of

A Very Big Sum - - Hacker Rank

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; }

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image_2

Step: 3

blur-text-image_3

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Oracle9i Database Administrator Implementation And Administration

Authors: Carol McCullough-Dieter

1st Edition

0619159006, 978-0619159009

More Books

Students also viewed these Databases questions