hihoCoder 简单计算器
2024-08-27 17:11:35
数据结构的入门题,理解倒是不复杂,用两个栈就行(一个存数字一个存符号)。对于我这样的弱弱没事练练编码能力还是不错的。
注意运算优先级即可。(过两天回科大了,下次再做题也不知道何时,ACM生涯两铜收场orz)
题目链接:
http://hihocoder.com/contest/hihointerview11/problem/3
代码:
#include <bits/stdc++.h> using namespace std;
typedef long long int64; stack<int64> sn;
stack<char> sc; const int maxn = + ;
char str[maxn]; char op[] = { '+', '-', '*', '/', '(', ')', '#' }; int getOpId(char op){
if(op == '+')
return -;
else if(op == '-')
return -;
else if(op == '*')
return -;
else if(op == '/')
return -;
else if(op == '(' )
return -;
else if(op == ')' )
return -;
else if(op == '#')
return -;
else if(op == '&')
return -;
} vector<int64> v; int getPrio(char op){
switch(op){
case '+': return ;
case '-': return ;
case '*': return ;
case '/': return ;
case '(': return ;
case '&': return ;
default: return ;
}
} int64 cal(int64 a, int64 b, char opt){
if(opt == '+'){
return a+b;
}else if(opt == '-'){
return a-b;
}else if(opt == '*'){
return a*b;
}else if(opt == '/'){
return a/b;
}
} int main(void){
scanf("%s", str);
int len = strlen(str);
str[len++] = '#'; for(int i = ; i < len; ++i){
if('' <= str[i] && str[i] <= ''){
int64 t = ;
while('' <= str[i] && str[i] <= ''){
t = t * + (str[i] - '');
i++;
}
i--;
v.push_back(t);
}else{
v.push_back(getOpId(str[i]));
}
//cout << v.back() << " ";
}
//cout << endl; int sz = v.size();
sc.push('&');
for(int i = ; i < sz; ++i){
if(v[i] >= ){
sn.push(v[i]);
//cout << "push " << v[i] << endl;
}else{
char c = op[-v[i]-];
if(c == '('){
sc.push('(');
//cout << "push " << '(' << endl;
}else if(c == ')'){
while(sc.top() != '('){
int64 b = sn.top(); sn.pop();
int64 a = sn.top(); sn.pop();
char opt = sc.top(); sc.pop();
sn.push(cal(a, b, opt));
//cout << "cal " << a << " " << opt << " " << b << endl;
}
sc.pop();
//cout << "pop " << '(' << endl;
}else{
int prio1 = getPrio(c);
int prio2; while(prio1 <= (prio2 = getPrio(sc.top()))){
//cout << "prio1: " << prio1 << " prio2: " << prio2 << endl;
int64 b = sn.top(); sn.pop();
int64 a = sn.top(); sn.pop();
char opt = sc.top(); sc.pop();
sn.push(cal(a, b, opt));
//cout << "cal " << a << " " << opt << " " << b << endl;
}
sc.push(c);
//cout << "push " << c << endl;
}
}
} //cout << "haha" << endl;
printf("%lld\n", sn.top()); return ;
} /**
5*(3+8*2)-(5+6*2-7)*2
100*(2+12)-(20/3)*2
(8+2*3/4-4)*(3-2+5/2*3)*(3-4+3)/6
*/
最新文章
- 【 2013 Multi-University Training Contest 2 】
- UML Sequence sample: if-else
- 获取 Chromium 源代码以及环境配置
- hdu4725最短路变形 添加点
- 20145212《Java程序程序设计》课程总结
- js框架简明
- Codeforces Round #177 (Div. 1) 题解【ABCD】
- linux获取目录下文件
- Android平台的四大天王:Activity, Service, ContentProvider, BroadcastReceiver
- JQ点击高亮显示
- chrom扩展学习
- margin负值-内秀篇
- node.js异步控制流程 回调,事件,promise和async/await
- CentOS系统搭建gitolite服务
- python打印万年历
- 安装好visual studio后,如何添加新的工作负载和组件
- 水晶报表Crystal 无效索引
- Yeoman安装和使用详解
- Redis 启动警告错误解决[转]
- 13.MD5对用户密码进行加密