题解 | #表达式求值#
表达式求值
https://www.nowcoder.com/practice/9566499a2e1546c0a257e885dfdbf30d
#include <iostream>
#include <string>
#include <stack>
// #include <cctype>
using namespace std;
int compute(string&s, int& left) //注意这里 要作为可改变的下标
{
int n = s.size();
int ans = 0;
char op = '+';
stack<int> st;
while(left<n)
{
if(s[left]=='(')
{
left++;
ans = compute(s, left); // 遇到括号 就计算后面那段的结果
}
while(left<n && isdigit(s[left]))
{
//是数字就转为一个整数
ans = s[left]-'0' + ans*10;
left++;
}
// 碰到计算符了 初始是+
switch (op)
{
case '+':
st.push(ans); // 本来站内数字就要相加 直接入栈
break;
case '-':
st.push(-ans);
break;
case '*':
{
// 当前数和栈顶做乘法
int tmp = st.top();
tmp *= ans;
st.pop(); // 出栈
st.push(tmp); // 乘积入栈
break;
}
case '/':
{
// 当前数和栈顶做除法
int tmp = st.top();
tmp /= ans;
st.pop();
st.push(tmp);
break;
}
}
if(left>=n) // 若已经遍历完 就跳出 适用于)在尾部的情况
{
break;
}
// 记录清空
ans = 0;
op = s[left]; // 真实的首个数字后的符号 每次只在这里获取操作符!
if(op==')')
{
left++;
//右括号
break;
}
left++;
}
// 操作完后 对栈内所有数字求和
int sum = 0;
while(st.size()>0)
{
sum+=st.top();
st.pop();
}
return sum;
}
int main() {
string dat;
cin>>dat;
int left = 0;
int ans = compute(dat, left);
cout<<ans;
}
// 64 位输出请用 printf("%lld")
查看7道真题和解析