15. 求字符串中所有整数的最小和

78 阅读1分钟

题目描述

输入字符串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;
}