icpc:problems:luogup6051
problems | |
---|---|
名称 | 求和 |
题目编号 | P6051 |
题目链接 | luogu.com.cn/… |
来源 | Luogu |
算法分类 | 字符串, 模拟 |
难易程度 | 容易 |
求和
想法
需要特别注意减号,减号可能作为间隔符号。当减号在开头,就不是间隔符。当减号不在开头并且前面没有数字,就不是间隔符。
代码实现
#include<iostream> #include<string> using namespace std; bool isnum(char x) { if(x >= '0' && x <= '9') return true; return false; } int main() { string str; while(getline(cin, str)) { int len = str.length(), temp = 0, flag = 1, sum = 0; bool havenum = false; for(int i=0; i<len; i++) { if(isnum(str[i])) { temp = temp * 10 + str[i] - '0'; havenum = true; continue; } if(temp != 0) sum += temp * flag; if(str[i] == '-' && ((i!=0 && !isnum(str[i-1])) || i == 0)) flag = -1; else flag = 1; temp = 0; } if(temp != 0) sum += temp * flag; if(havenum) cout << sum << '\n'; } return 0; }
/app/www/public/data/pages/icpc/problems/luogup6051.txt · 最后更改: 2024/03/09 12:39 由 温婕莺