题目描述
输入字符串s,输出s中包含所有整数的最小和。
说明:
字符串s,只包含 a-z A-Z ± ;
合法的整数包括
1) 正整数 一个或者多个0-9组成,如 0 2 3 002 102
2)负整数 负号 – 开头,数字部分由一个或者多个0-9组成,如 -0 -012 -23 -00023
输入描述
包含数字的字符串
输出描述
所有整数的最小和
用例
| 输入 | bb1234aa |
|---|---|
| 输出 | 10 |
| 说明 | 无 |
| 输入 | bb12-34aa |
|---|---|
| 输出 | -31 |
| 说明 | 1+2+(-34) = -31 |
C++源码
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
string str;
cin >> str;
string negative;
bool isNegative = false;
long long res = 0;
for (const char& c : str) {
if (isdigit(c)) {
if (isNegative) {
negative += c;
} else {
res += c-'0';
}
}else {
if (isNegative && negative.length() > 0) {
res -= stoll(negative);
negative.clear();
}
isNegative = (c == '-');
}
}
if (isNegative && negative.length() > 0) {
res -= stoll(negative);
}
cout << res << endl;
return 0;
}