Processing a string Problem Code: KOL15ASubmit
Given an alphanumeric string made up of digits and lower case Latin characters only, find the sum of all the digit characters in the string.
Input
- The first line of the input contains an integer T denoting the number of test cases. Then T test cases follow.
- Each test case is described with a single line containing a string S, the alphanumeric string.
Output
- For each test case, output a single line containing the sum of all the digit characters in that string.
Constraints
- 1 ≤ T ≤ 1000
- 1 ≤ |S| ≤ 1000, where |S| is the length of the string S.
Example
Input: 1 ab1231da Output: 7
Explanation
The digits in this string are 1, 2, 3 and 1. Hence, the sum of all of them is 7.
Solution in c++:
#include<iostream>
#include<stack>
using namespace std;
int sum(string exp);
bool IsNumber(char ch);
int main()
{
string exp;
int n;
cin >> n;
for (int i = 0; i < n; i++)
{
cin >> exp;
int result = sum(exp);
cout << result << endl;
}
return 0;
}
//
int sum(string exp)
{
stack<char> s;
int sum = 0;
for (int i = 0; i < exp.length(); i++)
{
if (IsNumber(exp[i]))
{
s.push(exp[i] - '0');
sum += s.top();
}
else
{
continue;
}
}
return sum;
}
//
bool IsNumber(char ch)
{
if (ch >= '0' && ch <= '9')
return true;
return false;
}
No comments:
Post a Comment