给出一个表达式,其中运算符仅包含+,-,*,/,^(加 减 乘 整除 乘方)要求求出表达式的最终值。

数据可能会出现括号情况,还有可能出现多余括号情况。

数据保证不会出现大于或等于231的答案。

数据可能会出现负数情况。

输入格式
输入仅一行,即为表达式。

输出格式
输出仅一行,既为表达式算出的结果。

输入样例:
(2+2)^(1+1)
输出样例:
16

#include<iostream>
#include<cstdio>
#include<stack>
using namespace std;
stack<int>nums;
stack<char>ops;
void calc()
{
    int a=nums.top();nums.pop();
    int b=nums.top();nums.pop();
    char c=ops.top();ops.pop();
    int d=1;
    if(c=='+')d=b+a;
    else if(c=='-')d=b-a;
    else if(c=='*')d=b*a;
    else if(c=='/')d=b/a;
    else{
        for(int i=0;i<a;i++)d*=b;
    }
    nums.push(d);
}
int main()
{
    string str,left;
    cin>>str;
    for(int i=0;i<str.size();i++)left+='(';
    str=left+str+')';
    for(int i=0;i<str.size();i++){
        char c=str[i];
        if(c>='0'&&c<='9'){
            int j=i,t=0;
            while(str[j]>='0'&&str[j]<='9'){
                t=t*10+str[j]-'0';
                j++;
            }
            nums.push(t);
            i=j-1;
        }else{
            
            if(c=='(')ops.push(c);
            else if(c=='+'||c=='-'){
                if(c=='-'&&i&&!(str[i-1]>='0'&&str[i-1]<='9'||str[i-1]==')')){
                    int j=i+1,t=0;
                    while(str[j]>='0'&&str[j]<='9'){
                        t=t*10+str[j]-'0';
                        j++;
                    }
                    nums.push(-t);
                    i=j-1;
                }else{
                    while(ops.top()!='(')calc();
                    ops.push(c);
                }
            }else if(c=='*'||c=='/'){
                while(ops.top()=='*'||ops.top()=='/'||ops.top()=='^')calc();
                ops.push(c);
            }else if(c=='^'){
                while(ops.top()=='^')calc();
                ops.push(c);
            }else if(c==')'){
                while(ops.top()!='(')calc();
                ops.pop();
            }
        }
    }
    cout<<nums.top()<<endl;
    return 0;
}


 posted on 2019-08-07 23:14  谁是凶手1703  阅读(1611)  评论(0)    收藏  举报