一道题,,写的代码巨长。。又是工程级代码 。。唉。。好不容易AC后看了看别人写的,30行。。崩溃啊。总是把问题想的特别复杂,或者说实现的特复杂。。。。
题目描述
所谓后缀表达式是指这样的一个表达式:式中不再引用括号,运算符号放在两个运算对象之后,所有计算按运算符号出现的顺序,严格地由左而右新进行(不用考虑运算符的优先级)。
如:3*(5–2)+7对应的后缀表达式为:3.5.2.-*7.+@。’@’为表达式的结束符号。‘.’为操作数的结束符号。
输入格式
输入:后缀表达式
输出格式
输出:表达式的值
输入输出样例
输入 #1
3.5.2.-*7.+@
输出 #1
16
说明/提示
字符串长度,1000内。
别人的栈里面存的是int类型的数,我存的都是char类型。心累啊。。存char类型还得判断负数和零的情况。WA了好多次。。长记性了
注释不删了。直接放上去了。。。
#include <iostream>
#include <stack>
#include <algorithm>
#include <cstring>
using namespace std;
int s[10000];
void change(int &a, stack<char>&st)
{
if(!st.empty() && st.top() == '.')
st.pop();
int tot = 0;
while(!st.empty() && st.top() != '.')
{
// cout << st.top() << endl;
if(st.top() != '-')
s[tot++] = st.top() - '0';
else
s[tot++] = st.top();
st.pop();
// a *= 10;
// a += st.top() - '0';
// st.pop();
}
int f = 0;
for(int i = tot - 1; i >= 0; i--)
{
if(s[i] == '-')
{
f = 1;
continue;
}
a *= 10;
a += s[i];
}
if(f)
a = -a;
// cout << a << endl;
// if(!st.empty())
// st.pop();
}
void cal(int a, int b, char c, int &num)
{
if(c == '+')
num = a + b;
if(c == '-')
num = a - b;
if(c == '*')
num = a * b;
if(c == '/')
num = a / b;
}
int main()
{
string str;
cin >> str;
int len = str.size();
stack<char>st;
for(int i = 0; i < len; i++)
{
// cout << str[i];
if(str[i] == '@')
break;
if((str[i] >= '0' && str[i] <= '9') || str[i] == '.')
st.push(str[i]);
if(str[i] == '+' || str[i] == '-' || str[i] == '*' || str[i] == '/')
{
char cur;
int a = 0, b = 0;
change(a, st);
change(b, st);
int num = 0;
cal(b, a, str[i], num);
int tot = 0;
// cout << a << " " << b << " " << num << endl;
int f = 0;
if(num < 0)
{
f = 1;
num = abs(num);
}
// cout << num;
if(num == '0')
st.push('0');
while(num)
{
s[tot++] = num % 10;
num /= 10;
}
// cout << 0000 << endl;
// for(int j = 0; j < tot; j++)
// cout << s[j];
// cout << endl;
// cout << num << endl;
if(f)
{
st.push('-');
}
for(int j = tot - 1; j >= 0; j--)
st.push(s[j] + '0');// cout << s[j] + '0';
if(!st.empty() && st.top() != '.')
st.push('.');
// cout << 23;
}
}
int num;
string cur;
// while(!st.empty())
// {
// cout << st.top();
// st.pop();
// }
while(!st.empty())
{
cur += st.top();
st.pop();
}
reverse(cur.begin(), cur.end());
for(int i = 0; i < cur.size(); i++)
if(cur[i] != '.')
cout << cur[i];
// cout << endl;
// change(num, st);
// cout << num;
return 0;
}
又写了个int型的版本。。。。
这对比…
#include <iostream>
using namespace std;
int a[1000];
int main()
{
int num = 0;
int tot = 0;
string str;
cin >> str;
for(int i = 0; i < str.size(); i++)
{
// cout << a[0] << ' ' << a[1] << " " << a[2] << endl;
if(str[i] >= '0' && str[i] <= '9')
a[tot] = a[tot] * 10 + str[i] - '0';
else if(str[i] == '.')
tot++;
else if(str[i] == '@')
break;
else
{
if(str[i] == '+')
a[tot - 2] = a[tot - 2] + a[tot - 1];
else if(str[i] == '-')
a[tot - 2] = a[tot - 2] - a[tot - 1];
else if(str[i] == '*')
a[tot - 2] *= a[tot - 1];
else if(str[i] == '/')
a[tot - 2] /= a[tot - 1];
tot--, a[tot] = 0;
}
}
cout << a[0];
return 0;
}