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;
}
计算
最新推荐文章于 2022-08-10 11:33:48 发布