-
Notifications
You must be signed in to change notification settings - Fork 2
/
number_search.cpp
38 lines (31 loc) · 1.19 KB
/
number_search.cpp
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
/*
Number Search
#search
Have the function NumberSearch(str) take the str parameter, search for all the numbers
in the string, add them together, then return that final number divided by the total
amount of letters in the string. For example: if str is "Hello6 9World 2, Nic8e D7ay!"
the output should be 2. First if you add up all the numbers, 6 + 9 + 2 + 8 + 7 you
get 32. Then there are 17 letters in the string. 32 / 17 = 1.882, and the final answer
should be rounded to the nearest whole number, so the answer is 2. Only single digit
numbers separated by spaces will be used throughout the whole string (So this won't
ever be the case: hello44444 world). Each string will also have at least one letter.
Optimal: o(n), achieved: o(n)
*/
#include <iostream>
#include <string>
#include <cmath>
int NumberSearch(std::string str) {
// code goes here
double sum{};
size_t cnt{};
for (const auto &el : str) {
if (isalnum(el) && isalpha(el)) {cnt++;}
else if (isalnum(el) && !isalpha(el)) {sum+=static_cast<int>(el)-48;}
}
return std::round(sum/cnt);
}
int main(void) {
// keep this function call here
std::cout << NumberSearch(coderbyteInternalStdinFunction(stdin));
return 0;
}