题解 | #表达式求值# 简单题?
表达式求值
https://www.nowcoder.com/practice/9566499a2e1546c0a257e885dfdbf30d
#include <cctype> #include <iostream> using namespace std; #include <vector> int compute(string& s, int left, int right) { char op = '+'; int num = 0; vector<int> st;//不含运算符的字问题结果 for (int i = left; i <= right; i++) { if (isdigit(s[i])) { //数字 num = num * 10 + s[i] - '0'; } if (s[i] == '(') { //括号 int layer = 0; int j = i; while (j <= right) { if (s[j] == '(') { layer++; } else if (s[j] == ')') { layer--; if (layer == 0) { break; } } j++;//定位到最外层的右括号 } num = compute(s, i + 1, j - 1); i = j + 1; } if(!isdigit(s[i])||i==right){//运算符或到头了 switch(op){ case '+':st.push_back(num);break; case '-':st.push_back(-num);break; case '*':st.back()*=num;break; case '/':st.back()/=num;break; } op=s[i];//更新运算符 num=0; //清空num } } int res=0; for(int n:st){ res+=n; } return res; } int main() { string s; while(cin>>s){ int ans=compute(s, 0, s.size()-1); cout<<ans<<endl; } return 0; } // 64 位输出请用 printf("%lld")