問題描述
輸入一個只包含加減乖除和括號的合法表達式,求表達式的值。其中除表示整除。
輸入格式
輸入一行,包含一個表達式。
輸出格式
輸出這個表達式的值。
樣例輸入
1-2+3*(4-5)
樣例輸出
-4
數據規(guī)模和約定
表達式長度不超過100,表達式運算合法且運算過程都在int內進行。
利用棧和后綴表達式來做
#include <bits/stdc++.h>
using namespace std;
char *infix2postfix(char *exp) {
char *postExp = new char[200];
int cnt = 0;
stack<char> st;
for(int i = 0; i < strlen(exp); i++) {
if(isdigit(exp[i])) {
postExp[cnt++] = exp[i];
} else {
if(isdigit(postExp[cnt-1])) {
postExp[cnt++] = '#';
}
if(exp[i] == '+' || exp[i] == '-') {
if(!st.empty()) {
while(!st.empty() && st.top() != '(') {
postExp[cnt++] = st.top();
st.pop();
}
}
st.push(exp[i]);
} else if(exp[i] == '*' || exp[i] == '/' || exp[i] == '(') {
st.push(exp[i]);
} else if(exp[i] == ')') {
while(st.top() != '(') {
postExp[cnt++] = st.top();
st.pop();
}
st.pop();
}
}
}
while(!st.empty()) {
postExp[cnt++] = st.top();
st.pop();
}
postExp[cnt] = 0;
return postExp;
}
int calculate(char *post) {
int ans = 0;
int a, b;
stack<int> st;
for (int i = 0; i < strlen(post); i++) {
a = b = 0;
if(isdigit(post[i])) {
while(isdigit(post[i])) {
b = post[i] - '0';
a = a * 10 + b;
i++;
}
if(post[i] != '#')
i--;
//cout << a << endl;
st.push(a);
} else {
a = st.top();
st.pop();
b = st.top();
st.pop();
switch(post[i]) {
case '+':
ans = a + b;
break;
case '-':
ans = b - a;
break;
case '*':
ans = a * b;
break;
case '/':
ans = b / a;
break;
}
//cout << ans << endl;
st.push(ans);
}
}
return ans;
}
int main() {
char exp[101];
char *postExp = new char[200];
scanf("%s", exp);
postExp = infix2postfix(exp);
//printf("%s\n", postExp);
printf("%d\n", calculate(postExp));
return 0;
}