1 条题解
-
-2
#include<bits/stdc++.h> using namespace std;int get_pr(char op) {switch (op) {case '^':return 4;case '*':case '/':return 3;case '+':case '-':return 2;case '(':return 0;default:return 0;}}bool is_r_a(char op) {return op == '^';}bool is_ops(char c) {return c == '+' || c == '-' || c == '*' || c == '/' || c == '^' || c == '(' || c == ')';}void calc(stack<long long>& nums, char op) {long long b = nums.top(); nums.pop();long long a = nums.top(); nums.pop();long long res = 0;switch(op){case '+':res=a+b; break;case '-':res=a-b; break;case '*':res=a*b; break;case '/':if (b==0){res=0;} else {res=a/b;}break;case '^':res=1;if (b>=0) {for(int i=0;i<b;i++) {res*=a;}}break;default:break;}nums.push(res);}int main() {string s;getline(cin,s);stack<long long> nums;stack<char> ops;int n=s.size();for(int i=0;i<n;i++){char c=s[i];if(isdigit(c)){//是否为数字long long num=0;while(i<n && isdigit(s[i])){num=num*10+(s[i]-'0');i++;}i--;nums.push(num);} else if(c=='('){ops.push(c);} else if(c==')'){while(!ops.empty() && ops.top()!='('){char op=ops.top();ops.pop();calc(nums,op);}ops.pop();} else if(is_ops(c)){if(c=='-'){if(i==0 || s[i-1]=='(' ||is_ops(s[i-1])){nums.push(0);}}while(!ops.empty() && ops.top()!='(' && ((get_pr(c)<get_pr(ops.top())) || (get_pr(c)==get_pr(ops.top()) && !is_r_a(c)))){char op=ops.top();ops.pop();calc(nums,op);}ops.push(c);}}while(!ops.empty()){char op=ops.top();ops.pop();calc(nums,op);}cout<<nums.top()<<endl;return 0;}
信息
- ID
- 371
- 时间
- 1000ms
- 内存
- 128MiB
- 难度
- 9
- 标签
- (无)
- 递交数
- 11
- 已通过
- 6
- 上传者