秋实大哥搞算数(字符串模拟)

N - 秋实大哥搞算数

Time Limit: 3000/1000MS (Java/Others)     Memory Limit: 65535/65535KB (Java/Others)
 

秋实大哥大学物理挂科了(误),于是在下学期的前两周的某一天要悲剧的补考。为了不给学校的挖掘机大楼做贡献,秋实大哥决定在假期里努力复习。当然,良好的计算能力也是非常必要的,毕竟是涉及计算自己做多少分的题能够通过考试的问题。现在他给自己出了一大堆长长的只有涉及整形四则运算式子,然后埋头计算结果。为了检验自己的计算能力,他请你来帮忙。

Input

第一行一个整数T,表示式子的总数。

接下来每一行有一个长度不超过10^6的表达式,只包含正整数和四则运算符号('+', '-', '*', '/')。

保证输入合法。

Output

对于每一个表达式,输出相应的结果,占一行。

保证运算及结果在long long范围以内。

Sample input and output

Sample Input Sample Output
2
12+5/4-1
4*5/3
12
6
思路:
首先算完所有的乘除法,在算一遍加减法就完成了。

AC代码:

#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdio>
#include<vector>
#include<stack>
using namespace std;
typedef long long ll;

#define T 1000000+50

char s[T];
ll tmp;
ll st[T],top1=0,top2=0;
char sta[T];
int main()
{
#ifdef zsc
	freopen("input.txt","r",stdin);
#endif

	int n,m,i,j,k;
	scanf("%d",&n);
	while(n--)
	{
		top1=0,top2=0;
		scanf("%s",s);
		tmp = 0;
		for(i=0;s[i];++i){
			if(s[i]>='0'&&s[i]<='9')tmp = tmp*10 + s[i]-'0';
			else {
				st[top1++] = tmp;
				tmp = 0;
				sta[top2++] = s[i];
			}
		}
		st[top1++] = tmp;
		int head = 0;
		//首先将全部的乘除法算完
		for(i=0;i<top2;++i,head++){
			if(sta[i]=='*'){
				st[head+1] = st[head]*st[head+1];
				st[head] = -1;
				sta[i] = '0';
			}
			else if(sta[i]=='/'){
				st[head+1] = st[head]/st[head+1];
				st[head] = -1;
				sta[i] = '0';
			}
		}
		//之后就是解决加减法
		stack<ll> ys;head = 0;
		for(i=0;i<top1;++i){
			if(st[i]>=0){
				ys.push(st[i]);
			}
			if(ys.size()==2){
				while(head<top2)
				{
					if(sta[head]=='+'){
						ll t1 = ys.top();ys.pop();
						ll t2 = ys.top();ys.pop();
						ys.push(t1+t2);
						head++;
						break;
					}
					if(sta[head]=='-'){
						ll t1 = ys.top();ys.pop();
						ll t2 = ys.top();ys.pop();
						ys.push(t2-t1);
						head++;
						break;
					}
					head++;
				}
			}
		}
		printf("%lld\n",ys.top());
	}
	return 0;
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值