알고리즘/codefights

54>sumUpNumbers

Diademata 2018. 3. 14. 23:04
반응형

CodeMaster has just returned from shopping. He scanned the check of the items he bought and gave the resulting string to Ratiorg to figure out the total number of purchased items. Since Ratiorg is a bot he is definitely going to automate it, so he needs a program that sums up all the numbers which appear in the given input.

Help Ratiorg by writing a function that returns the sum of numbers that appear in the given inputString.


Example


For inputString = "2 apples, 12 oranges", the output should be

sumUpNumbers(inputString) = 14.


code>>


int sumUpNumbers(std::string inputString) {

std::regex re("([0-9]+)");

std::smatch m;

int sum = 0;

while (std::regex_search(inputString, m, re))

{

sum += std::atoi(m[0].str().c_str());

inputString = m.suffix();

}

return sum;

}



반응형