PIPIOJ-1362-计算表达式

题目描述
对于一个不存在括号的表达式进行计算(包含加减乘除四种运算符,除法为向下取整)。
输入
多组数据,每组数据占据一行。
输出
输出计算结果。
样例输入
6/2+3+34
734/2-56
2-7*8
样例输出
18
199

// 题目:计算表达式
// 日期:2021/7/13
// 详情:对于一个不存在括号的表达式进行计算(包含加减乘除四种运算符,除法为向下取整)。
// XWQ 
#include <bits/stdc++.h>
using namespace std;
int help(int a, int b, char op){
	switch (op){
		case '+':
			return a+b;
		case '-':
			return a-b;
		case '*':
			return a*b;
		case '/':
			return a/b;
	}
	return 0;
}
int cal(string str){
	stack<int> num;
	stack<char> op;
	int priority[300];
	priority['+'] = priority['-'] = 0;
	priority['/'] = priority['*'] = 1;
	
	int n = str.size(),a,b,now=0;
	for(int i=0; i<n; i++){
		if(str[i]>='0' && str[i]<='9')	// 1.数字入num栈 
			now = now*10 + str[i] - '0';	// 1*.转换多位数 
		else{	// 2.符号 
			num.push(now);
			now = 0;
			if(!op.empty()){
				while(!op.empty() && priority[str[i]]<=priority[op.top()]){	// 2*.根据优先级计算 
					a = num.top(); num.pop();
					b = num.top(); num.pop();
					num.push(help(b,a,op.top()));
					op.pop();
				}
			}			
			op.push(str[i]);
		}
	}
	num.push(now);
	while(!op.empty()){	// 3.计算剩余栈内的表达式 
		int a = num.top(); num.pop();
		int b = num.top(); num.pop();
		num.push(help(b,a,op.top()));
		op.pop();
	}
	return num.top();
}
int main(){
	string str;
	while(cin >> str){
		printf("%d\n",cal(str));
	}
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值