Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Latest commit

 

History

History
History
55 lines (41 loc) · 1.14 KB

File metadata and controls

55 lines (41 loc) · 1.14 KB
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include "StringCalculator.h"
class GetNegatives {
private:
string negatives;
public:
void operator()(int i) {
if (i < 0)
negatives.append(to_string(i) + ",");
}
operator string() {
if (negatives.length() > 0)
negatives.pop_back();
return negatives;
}
};
void check_for_negatives(const vector<int> &numbers) {
string negatives = for_each(numbers.begin(), numbers.end(), GetNegatives());
if (negatives.size() > 0) {
throw invalid_argument("Negatives not allowed: " + negatives);
}
}
void add_if_valid(vector<int> &numbers, string number_string) {
int number = stoi(number_string);
if (number <= 1000)
numbers.push_back(number);
}
vector<int> get_numbers(const string &input) {
regex numbers_only("(-?\\d+)+");
vector<int> numbers;
for_each(sregex_token_iterator(input.begin(), input.end(), numbers_only),
sregex_token_iterator(),
[&numbers](string s) { add_if_valid(numbers, s); });
return numbers;
}
int StringCalculator::Add(const string &input) {
if (input.empty())
return 0;
vector<int> numbers = get_numbers(input);
check_for_negatives(numbers);
return accumulate(numbers.begin(), numbers.end(), 0);
}
Morty Proxy This is a proxified and sanitized view of the page, visit original site.