题目描述
小明在你的帮助下,破密了Ferrari设的密码门,正要往前走,突然又出现了一个密码门,门上有一个算式,其中只有“(”,“)”,“0-9”,“+”,“-”,“*”,“/”,“^”求出的值就是密码。小明数学学得不好,还需你帮他的忙。(“/”用整数除法,取商)
输入
输入共1行,为一个算式。
输出
输出共1行,就是密码。
样例输入
1+(3+2)*(7^2+6*9)/(2)
样例输出
258
提示
100%的数据满足:算式长度<=30 其中所有数据在231-1的范围内。
//
// main.cpp
// 2
//
// Created by 5201-mac on 17/7/20.
// Copyright © 2017年 5201-mac. All rights reserved.
//
#include <iostream>
#include <stack>
#include <cstdio>
#include <cstring>
using namespace std;
stack<char>m;
stack<long long>n;
int mycomp(char c)
{
char b;
b=m.top();
if(c=='+'||c=='-')
{
if(b=='+'||b=='-'||b=='*'||b=='/'||b=='^')
return 1;
else
return -1;
}
else if(c=='*'||c=='/')
{
if(b=='*'||b=='/'||b=='^')
return 1;
else
return -1;
}
else if(c=='^')
{
if(b=='^')
return 1;
else
return -1;
}
else if(c=='(')
return -1;
else if(c==')')
{
if(b=='(')
return 0;
else
return 1;
}
else if(c=='#')
{
if(b=='#')
return 0;
else
return 1;
}
return 0;
}
int main() {
char a[100],b;
m.push('#');
scanf("%s",a);
int t=(int)strlen(a);
for(int i=0;i<=t;i++)
{
if(i==t)
a[i]='#';
if(a[i]>='0'&&a[i]<='9')
{
long long w=a[i]-'0';
while(1)
{
i++;
if(a[i]>='0'&&a[i]<='9')
w=w*10+a[i]-'0';
else
break;
}
if(a[i]=='\0'||a[i]=='\n')
a[i]='#';
n.push(w);
}
if(a[i]<'0'||a[i]>'9')
{
int v=mycomp(a[i]);
while(v==1)
{
long long x,y;
x=n.top();
n.pop();
y=n.top();
n.pop();
b=m.top();
m.pop();
if(b=='+')
y+=x;
else if(b=='-')
y-=x;
else if(b=='*')
y*=x;
else if(b=='/')
y/=x;
else
{
long long a=y;
x--;
while(x--)
y=y*a;
}
n.push(y);
v=mycomp(a[i]);
}
if(v==-1)
m.push(a[i]);
else
{
b=m.top();
if(b=='#')
{
if(!n.empty())
{
printf("%lld\n",n.top());
n.pop();
}
m.pop();
break;
}
else
{
m.pop();
}
}
}
}
// insert code here...
//std::cout << "Hello, World!\n";
return 0;
}
/**************************************************************
Problem: 1590
User: 2015014139
Language: C++
Result: 正确
Time:3 ms
Memory:1696 kb
****************************************************************/