算法训练 表达式计算
来源:互联网 发布:政府数据库 编辑:程序博客网 时间:2024/05/21 09:10
#include <iostream>#include <string>#include <sstream>#include <stack>#include <cctype>using namespace std;stack<int> stack_num;stack<char> stack_op;bool f(char ch1, char ch2){ // 1-2+3 1*2/3 if ((ch1 == '-'||ch1 == '+') && (ch2 == '+'|| ch2 == '-') ) return false; if ((ch1 == '*' || ch1 == '/') && (ch2 == '*' || ch2 == '/')) return false; // 1*2-3 if ((ch1 == '*' || ch1 == '/') && (ch2 == '+' || ch2 == '-')) return false; // 1+2*3 if ((ch1 == '+' || ch1 == '-') && (ch2 == '*' || ch2 == '/')) return true;}int calc(int num1, int num2, char op){ int ret = 0; switch (op) { case '+': ret = num1 + num2; break; case '-': ret = num1 - num2; break; case '*': ret = num1 * num2; break; case '/': ret = num1 / num2; break; default: break; } return ret;}// 5*((1-2)*(6-7+8*9-(34-12*1)))// 1-2+3*(4-5)int main(){ string str; cin >> str; for (unsigned int i = 0; i < str.length(); i++){ if (isdigit(str[i])){ string tmp = ""; stringstream ss; int k; while (isdigit(str[i])){ tmp += str[i]; i++; } i-=1; ss << tmp; ss >> k; stack_num.push(k); }else{ if (stack_op.empty() || str[i] == '('){ stack_op.push(str[i]); }else{ if (str[i] == ')'){ while (stack_op.top() != '(') { int num1, num2; if (!stack_num.empty()){ num2 = stack_num.top(); stack_num.pop(); }else{ num2 = 0; } if (!stack_num.empty()){ num1 = stack_num.top(); stack_num.pop(); }else{ num1 = 0; } char op = stack_op.top(); stack_op.pop(); stack_num.push(calc(num1, num2, op)); } stack_op.pop(); // 除去stack_op 中的 ( }else{ char ch1 = stack_op.top(); char ch2 = str[i]; if (f(ch1, ch2)){ stack_op.push(str[i]); }else{ int num2 = stack_num.top(); stack_num.pop(); int num1 = stack_num.top(); stack_num.pop(); int s = calc(num1, num2, stack_op.top()); stack_op.pop(); stack_num.push(s); stack_op.push(str[i]); } // end if (f(ch1,ch2)) } } } } // 清空尾数据 while (!stack_op.empty()){ int num1, num2; if (!stack_num.empty()){ num2 = stack_num.top(); stack_num.pop(); }else{ num2 = 0; } if (!stack_num.empty()){ num1 = stack_num.top(); stack_num.pop(); }else{ num1 = 0; } char op = stack_op.top(); stack_op.pop(); stack_num.push(calc(num1, num2, op)); } cout << stack_num.top() << endl; return 0;}
阅读全文
0 0
- 算法训练 表达式计算
- 算法训练 表达式计算
- 算法训练 表达式计算
- 算法训练 表达式计算
- 算法训练 表达式计算
- 算法训练 表达式计算
- 算法训练 表达式计算
- 算法训练 表达式计算
- 算法训练 表达式计算
- 算法训练 表达式计算
- 算法训练 表达式计算
- 蓝桥杯算法训练 表达式计算
- 蓝桥杯--算法训练 表达式计算
- 蓝桥杯 算法训练 表达式计算
- 蓝桥杯 算法训练-表达式计算
- 蓝桥杯 算法训练 表达式计算
- 蓝桥杯 算法训练 表达式计算
- 算法训练 表达式计算 ——蓝桥杯
- C程序之早起
- Android MVP封装模拟登陆
- mvp基类
- 传感器01
- CIA3 NOI接站(tarjan缩环+Floyd传递闭包+可相交最小路径覆盖)
- 算法训练 表达式计算
- mvp(okhttp)请求图片与数据
- 简单注册登录请求
- form表单验证,提交数据显示
- 第二个综合题的布局文件
- 《挑战程序设计竞赛》 P2 题目:抽签 优化,优化,再优化
- HashTable、HashSet和Dictionary的区别
- 第二个综合题的mainactivity
- MVP登录注册