计算

来源:互联网 发布:段宁毛笔行书 mac 编辑:程序博客网 时间:2024/04/29 00:41

Problem Description

小明在你的帮助下,破译了Ferrari设的密码门,正要往前走,突然又出现了一个密码门,门上有一个算式,其中只有“(”、“)”、“0-9”、“+”、“-”、“*”、“/”、“^”,求出的值就是密码。小明的数学学得不好,还需你帮他的忙。(“/”用整数除法)

Input

输入的第一行为T,表示测试示例的个数,每组数据只有一行是一个算式(算式长度<=30)。

Output

对于每组数据,输出算式的值(所有数据在2^31-1内)。

Sample Input

11+(3+2)*(7^2+6*9)/(2)

Sample Output

258

Author

HYNU

# include <cstdio># include <stack>using namespace std;char s[110];stack < int > a;stack < char > c;int cmp(char c)    //判断优先级{    if(c=='-'||c=='+')    return 1;    if(c=='*'||c=='/')    return 2;    if(c=='^')    return 3;    if(c=='(')   return 0;}void calculate(stack <int> &n,stack <char> &m)    //计算;{    int a,b,ans,i;    char c;    a=n.top();    n.pop();    b=n.top();    n.pop();    c=m.top();    m.pop();    if(c=='+')    ans=a+b;    if(c=='-')    ans=b-a;    if(c=='*')    ans=a*b;    if(c=='/')    ans=b/a;    if(c=='^')    {        ans=1;        for(i=1;i<=a;i++)    ans*=b;    }    n.push(ans);}int main(){    freopen("a.txt","r",stdin);    int t;    scanf("%d",&t);    while(t--)    {        scanf("%s",s);        int i,num=0,flag=0;        for(i=0;s[i]!='\0';i++)        {            if(s[i]>='0'&&s[i]<='9')   {num=num*10+s[i]-'0';   flag=1;}            else            {                if(flag)    {a.push(num);    num=0; flag=0;}                if(s[i]=='(')    {c.push('(');   continue;}                if(s[i]==')')                {                    while(c.top()!='(')    calculate(a,c);                    c.pop();                    continue;                }                if(c.empty())    c.push(s[i]);                else                {                    while(!c.empty()&&cmp(c.top())>=cmp(s[i]))    calculate(a,c);                    c.push(s[i]);                }            }        }        if(flag)    {a.push(num);    num=0;   flag=0;}        while(!c.empty())    calculate(a,c);        printf("%d\n",a.top());        a.pop();    }    return 0;}
0 0
原创粉丝点击