四则

1.处理字符串,使{}[]转化为(),若-之前为({[]})则在其前面加0


#include <iostream>

#include <string>
#include <stack>
#include <deque>
#include <sstream>
using namespace std;


class Cal{
public:


void preprocess(string& str)
{
for (string::size_type i = 0; i != str.size();i++)
{
if (str[i] == '[' || str[i] == '{')
str[i] = '(';
else if (str[i] == ']' || str[i] == '}')
str[i] = ')';
else if (str[i] == '-')
{
if (i == 0)
str.insert(0, 1, '0');
else if (str[i - 1] == '(')
str.insert(i,1,'0');
}
}
}
bool ispra(string s)
{
if (s == "(" || s == ")")
return true;
else
return false;
}
int getpriority(string s)
{
int res = 0;
if(s=="+"||s=="-")
return 1;
else if(s=="*"||s=="/")
return 2;
else if(s=="("||s==")")
return -1;
return res;
}
void check(string s,stack<string>& opt,deque<string>& col2)
{
if (opt.empty())
{
opt.push(s);
return;
}
if (ispra(s))
{
if (s == "(")
{
opt.push(s);
}
else
{
while (opt.top()!="(")
{
string stemp= opt.top();
col2.push_back(stemp);
opt.pop(); 
}
opt.pop();
}
}
else
{
string chtop = opt.top();
if(getpriority(s)<=getpriority(chtop))
{
col2.push_back(chtop);
opt.pop();
check(s,opt,col2);
}
else
opt.push(s);
}


}
void allocate(string& str, deque<string>& col2)
{
stack<string> opt;
int len=str.size();
for(int i=0;i<len;i++)
{
string temp="";
if (str[i]>='0'&& str[i]<='9')
{
temp+=str[i];
while(i+1<len&&str[i+1]>='0'&&str[i+1]<='9')
{
i++;
temp+=str[i];
}
col2.push_back(temp);
}
else
{
temp+=str[i];
check(temp,opt,col2);
}
}
while (!opt.empty())
{
col2.push_back(opt.top());
opt.pop();
}
}
int cal(int v1, char opt, int v2)
{
int res = 0;
switch (opt)
{
case '+':
res = v1 + v2;
break;
case '-':
res = v1 - v2;
break;
case '*':
res = v1*v2;
break;
case '/':
res = v1 / v2;
break;
}
return res;
}
int calculate(string str)
{
preprocess(str);


//deque<char> col1(str.begin(), str.end()); //中缀
deque<string> col2; //后缀
stack<int> value;


allocate(str,col2);
while (!col2.empty())
{
string s= col2.front();
col2.pop_front();
if (s[0] >= '0' && s[0] <= '9')
{
stringstream ss(s);
int temp=0;
ss>>temp;
value.push(temp);
}
else
{
int v2 = value.top();
value.pop();
int v1 = value.top();
value.pop();
char ch=s[0];
value.push(cal(v1, ch, v2));
}
}
return value.top();
}
};
int main()
{
string str;
while (cin>>str)
{
Cal test;
cout << test.calculate(str) << endl;
str.clear();
}
return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值