求和

P6051 [RC-02] 求和 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)

  • 字符串练习题
  • 根据题意找到可能是数字的入口,再从入口进入while循环找到其后跟着的多位数字组成整个数字
// https://www.luogu.com.cn/problem/P6051
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define MAX 10000001
string s;
char temp[MAX];
int ans, k;
int main()
{
    while (getline(cin, s))
    {
        ans = 0;
        bool have_num = false;
        for (int i = 0; i < s.length(); i++)
        {
            if (i && isdigit(s[i - 1]) && !isdigit(s[i]))
                continue;
            if (s[i] == '-' && i < s.length() - 1 && isdigit(s[i + 1]))
            {
                k = 0;
                have_num = true;
                temp[k++] = s[i];
                i++;
                while (i < s.length() && isdigit(s[i]))
                {
                    temp[k++] = s[i];
                    i++;
                }
                temp[k] = 0;
                ans += atoi(temp);
                continue;
            }
            if (isdigit(s[i]))
            {
                k = 0;
                have_num = true;
                temp[k++] = s[i];
                i++;
                while (i < s.length() && isdigit(s[i]))
                {
                    temp[k++] = s[i];
                    i++;
                }
                temp[k] = 0;
                ans += atoi(temp);
                continue;
            }
        }
        if (have_num)
        {
            cout << ans << endl;
        }
    }
}

 

posted on 2022-08-11 08:58  樵风  阅读(78)  评论(0)    收藏  举报