表达式求值
2016-03-24 21:07
323 查看
题目描述
利用栈来实现含有加,减,乘,除等基本运算,输出表达式的值
输入
3*(15/5)+8=
输出
17
样例输入
24-(6+(27/3)*2)=
样例输出
0
AC代码:
#include<cstdio> #include<cstring> #include<stack> using namespace std; int main() { int T,i,len; int x,y,flat; char str[100]; stack<int>n; stack<char>c; scanf("%s",str); len=strlen(str); for(i=0;i<len;){ if(str[i]>='0'&&str[i]<='9'){ flat=0; while(str[i]>='0'&&str[i]<='9'){ flat=flat*10+str[i]-'0'; i++; } n.push(flat); } else if(str[i]=='('){ c.push(str[i]); i++; } else if(str[i]=='+'||str[i]=='-'){ if(!c.empty()&&c.top()!='('){ x=n.top(); n.pop(); y=n.top(); n.pop(); if(c.top()=='+')n.push(x+y); else if(c.top()=='-')n.push(y-x); else if(c.top()=='*')n.push(x*y); else if(c.top()=='/')n.push(y/x); c.pop(); } else{ c.push(str[i]); i++; } } else if(str[i]=='*'||str[i]=='/'){ if(!c.empty()&&c.top()!='('){ if(c.top()=='+'||c.top()=='-'){ c.push(str[i]); i++;continue; } else{ x=n.top(); n.pop(); y=n.top(); n.pop(); if(c.top()=='*')n.push(x*y); else n.push(y/x); c.pop(); } } else{ c.push(str[i]); i++; } } else if(str[i]==')'){ while(c.top()!='(') { x=n.top(); n.pop(); y=n.top(); n.pop(); if(c.top()=='-') n.push(y-x); else if(c.top()=='+') n.push(x+y); else if(c.top()=='*') n.push(x*y); else n.push(y/x); c.pop(); } c.pop(); i++; } else if(str[i]=='=') { if(!c.empty()) { while(!c.empty()) { x=n.top(); n.pop(); y=n.top(); n.pop(); if(c.top()=='-'){ n.push(y-x); i++; } else if(c.top()=='+'){ n.push(x+y); i++; } else if(c.top()=='*'){ n.push(x*y); i++; } else if(c.top()=='/'){ n.push(y/x); i++; } c.pop(); } } else i++; } } printf("%d\n",n.top()); n.empty(); c.empty(); return 0; }
相关文章推荐
- 方法的直接调用,反射调用与……Lambda表达式调用
- 配置spark开发环境1——资源准备
- 网易互娱2017实习生招聘在线笔试第一场-电子数字
- 体验孤独
- TCP基础知识
- leetcode 144. Binary Tree Preorder Traversal
- LeetCode#101. Symmetric Tree
- Python实现的淘宝直通车数据抓取(3)
- POJ 3254 状压dp
- hdu1452 Happy 2004(规律+因子和+积性函数)
- SAS基础数据管理
- js遍历表格数据
- XML扩展性标记语言
- 我遇到的面试题
- PHP实用方法
- iOS资源汇总(开源项目、第三方库、技术博客等)
- 1.9-Redis持久化
- C#——判断一个数是奇偶性
- 修改button的text
- 面试题汇总