计算

Problem Description
小明在你的帮助下,破译了Ferrari设的密码门,正要往前走,突然又出现了一个密码门,门上有一个算式,其中只有“(”、“)”、“0-9”、“+”、“-”、“*”、“/”、“^”,求出的值就是密码。小明的数学学得不好,还需你帮他的忙。(“/”用整数除法)
Input
输入有多组数据,每组数据只有一行是一个算式(算式长度<=30)。
Output
对于每组数据,输出算式的值(所有数据在2^31-1内)。
Sample Input
1
1+(3+2)*(7^2+6*9)/(2)
Sample Output
258
//标程:
#include<stdio.h>
#include<string.h>
#include<stack>
using namespace std;


int f(char c)
{
     if(c=='+'||c=='-') return 1;
     if(c=='*'||c=='/') return 2;
     if(c=='^') return 3;
     if(c=='(') return 0;
}
void  js(stack<int> &s1, stack<char> &s2)
{
    int x,y,ans=1,i;
    char ch;
    x=s1.top(); s1.pop();
    y=s1.top(); s1.pop();
    ch=s2.top(); s2.pop();
    if(ch=='+') s1.push(y+x);
    if(ch=='-') s1.push(y-x);
    if(ch=='*') s1.push(y*x);
    if(ch=='/') s1.push(y/x);
    if(ch=='^')
    {
        for(i=0;i<x;i++) ans*=y;
        s1.push(ans);
    }
}
int main()
{
	//freopen("a.txt","r",stdin);
	int n;
	char s[50];
	scanf("%d\n",&n);
	while(n--)
	{
		stack<int>  si;
		stack<char>  sc;
		gets(s);
		int len=strlen(s),i,flag=0,temp=0;
        
		for(i=0;i<len;i++)
		{
			if(s[i]>='0' && s[i]<='9')
			{
				temp=temp*10+s[i]-'0';
				flag=1;
			}
			else 
			{
				  if(flag) { si.push(temp); temp=0; flag=0;}
				  if(s[i]=='(') {  sc.push(s[i]);  continue;}
				  if(s[i]==')')
				  {
					  while(sc.top()!='(')     js(si,sc); 
					  sc.pop();
				      continue;
				  }
				if(sc.empty())  sc.push(s[i]);
				else 
				{
					while(!sc.empty() && f(sc.top())>=f(s[i]))	js(si,sc); 
					sc.push(s[i]);
				}
			}
		}
		if(flag) { si.push(temp); temp=0; flag=0;}
		while(!sc.empty()) js(si,sc);
        printf("%d\n",si.top());
		si.pop();
	}
	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值