Problem :
In this challenge, you are required to 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 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 :
- int: 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.
Constraints :
1 <= n <= 10
0 <= ar[i] <= 10^10
Sample Input :
5
1000000001 1000000002 1000000003 1000000004 1000000005
Output :
5000000015
Note :
When we add several integer values, the resulting sum might exceed the above range. You might need to use long int C/C++/Java to store such sums.
Solution :
#include <bits/stdc++.h>
using namespace std;
vector<string> split_string(string);
// Complete the aVeryBigSum function below.
long aVeryBigSum(vector<long> ar) {
long sum = 0;
sum = accumulate(ar.begin(),ar.end(),0LL);
return sum;
}
int main()
{
ofstream fout(getenv("OUTPUT_PATH"));
int ar_count;
cin >> ar_count;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
string ar_temp_temp;
getline(cin, ar_temp_temp);
vector<string> ar_temp = split_string(ar_temp_temp);
vector<long> ar(ar_count);
for (int i = 0; i < ar_count; i++) {
long ar_item = stol(ar_temp[i]);
ar[i] = ar_item;
}
long result = aVeryBigSum(ar);
fout << result << "\n";
fout.close();
return 0;
}
vector<string> 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<string> 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;
}
125 total views, 1 views today
Post Disclaimer
the above hole problem statement is given by hackerrank.com but the solution is generated by the SLTECHACADEMY authority if any of the query regarding this post or website fill the following contact form thank you.