3 条题解
-
0
#include <bits/stdc++.h> using namespace std; using ll = long long; int main() { ios::sync_with_stdio(0), cin.tie(0), cout.tie(0); string s; cin >> s; vector<ll> nums; vector<char> ops; int i = 0; int n = s.size(); while (i < n) { if (isdigit(s[i])) { ll num = 0; while (i < n && isdigit(s[i])) { num = num * 10 + (s[i] - '0'); i++; } nums.push_back(num % 10000); } else { ops.push_back(s[i]); i++; } } if (nums.empty()) { cout << 0 << endl; return 0; } ll sum = 0; ll temp = nums[0]; for (size_t j = 0; j < ops.size(); ++j) { char op = ops[j]; ll num = nums[j + 1]; if (op == '+') { sum = (sum + temp) % 10000; temp = num; } else if (op == '*') { temp = (temp * num) % 10000; } } sum = (sum + temp) % 10000; cout << sum << '\n'; return 0; }
-
0
#include <bits/stdc++.h> #define objl '\n' typedef long long ll; using namespace std; //数据结构在这里定义 int mod = 10000; stack<ll> num_st;//数字栈 stack<char> char_st;//符号栈 string s; //保存不同符号的优先级 map<char, int> mp = {{'+',1},{'-',1},{'*',2},{'/',2}}; int solve(){ //cin cout在这里 cin >> s; //记录下一个数字的信息 ll tmp = 0; bool flag = false; for(int i = 0; i < s.size();i++){ if(s[i] >= '0'&& s[i] <= '9'){ tmp = tmp * 10 + s[i] - '0'; flag = true; }else{//处理符号 //先把符号前面的数字入栈 if(flag == true){ num_st.push(tmp); tmp = 0; flag = false; } //如果符号栈内还有符号,先把优先级大于本符号的先弹栈运算 while(!char_st.empty() && mp[s[i]] < mp[char_st.top()]){ char c = char_st.top(); char_st.pop(); //如果一个符号没有对应两个操作数表达式有误 if(num_st.size()<2) return -1; ll right = num_st.top(); num_st.pop(); ll left = num_st.top(); num_st.pop(); ll res; if(c=='+'){ res = (left % mod + right % mod) % mod; }else if(c=='*'){ res = (left % mod * right % mod) % mod; } num_st.push(res); } //处理完优先级更高的运算把本符号入栈 char_st.push(s[i]); } } //把最后一个数字入栈 if(flag == true) num_st.push(tmp); //处理符号栈剩余字符,从右往左计算同优先级的表达式 while(!char_st.empty()){ char c = char_st.top(); char_st.pop(); if(num_st.size()<2) return -1; ll right = num_st.top(); num_st.pop(); ll left = num_st.top(); num_st.pop(); ll res; if(c=='+'){ res = (left % mod + right % mod) % mod; }else if(c=='*'){ res = (left % mod * right % mod) % mod; } num_st.push(res); } //正确的表达式 符号栈为空 数字栈只剩下一个结果 if(num_st.size()==1&&char_st.empty()) return num_st.top() % mod; else return -1; } int main(){ ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); int t;//多组数据要cin //cin >> t; t = 1; while(t--){ int res = solve(); cout << res << endl; } return 0;//必须加return 0 }
- 1
信息
- ID
- 107
- 时间
- 1000ms
- 内存
- 256MiB
- 难度
- 5
- 标签
- 递交数
- 162
- 已通过
- 60
- 上传者