牛客简单模拟 奇怪的计算器

奇怪的计算器题目链接
题目描述
牛牛家里有一个计算器。
牛牛不小心把自己的计算器玩坏了。乘法(×)和除法(÷)按钮全都失灵。
所以,牛牛决定以后用它来计算只含加(+)和减(-)的表达式。
最近,牛牛突然发现,这个计算器的幂(^)按钮变成了异或键!本来 5^2=25 的,现在 5^2=7 了。
因此他想知道,输入一个表达式后计算器会返回多少。
该计算器认为优先级异或(^)>加(+),减(-)。
输入描述
输入一串表达式,保证该字符串只含数字,+,-,^,且每个数字 <= 1000000
输出描述
输出答案。
输入样例

3+5^2-9

输出样例

1

s i z e size size 表示表达式长度,保证表达式合法且 符号个数 + 1 = 数的个数 。对于所有的数据 1 ≤ s i z e ≤ 1 0 6 1≤size≤10^6 1size106

先把字符串转换,首先符号如果是 + + + 或者 − - 则存入栈中,然后把对应的数字字符转换数字,如果查找过程中遇到符号是 ^,则弹出一个数,然后紧接着计算下一个数,两个数异或一下存入栈中,然后把字符栈和数字栈中的元素弹出存入新的容器,最后按照顺序加或者减按照顺序求结果。

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
stack<ll>num,ans;
stack<char>fu,res;
int main()
{
    
    
    string s;
    cin>>s;
    int len = s.size();
    for(int i = 0; i < len; i++)
    {
    
    
        ll t = 0; int ok = 0;
        if(s[i] == '+' || s[i] == '-') fu.push(s[i]);
        else{
    
    
            while(s[i] >= '0' && s[i] <= '9' && i < len)
            {
    
    
                t = t*10 + s[i] - '0';
                i++;
                ok  = 1;
            }
            if(ok) num.push(t);
            if(ok && s[i] != '^') i--;
            if(s[i] == '^')
            {
    
    
                ll x = num.top(); num.pop();
                t = 0;
                while(s[i+1] >= '0' && s[i+1] <= '9' && i+1 < len)
                {
    
    
                    t = t*10 + s[i+1] - '0';
                    i++;
                }
                ll temp = x^t;
                num.push(temp);
            }
        }
    }
    while(!fu.empty())
    {
    
    
        char tx = fu.top(); fu.pop();
        res.push(tx);
    }
    while(!num.empty())
    {
    
    
        ll tx = num.top(); num.pop();
        ans.push(tx);
    }
    while(res.size()>0)
    {
    
    
        char st = res.top(); res.pop();
        ll x = ans.top(); ans.pop();  //9
        ll y = ans.top(); ans.pop();   //7
        if(st == '+') ans.push(x+y);
        if(st == '-') ans.push(x-y);
    }
    cout<<ans.top()<<'\n';
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Edviv/article/details/111304740