重返小学(板子计算器+-*/^!)

重返小学

#include<bits/stdc++.h>
using namespace std;

const int N = 66666;

#define int long long
#define mod 65536

int f[N];
stack<char> ops;
stack<int> num;
unordered_map<char, int> mp = {{'+', 1}, {'-', 1}, {'*', 2}, {'/', 2}, {'^', 3}, {'!', 4}};



bool flag = false;
int ksm(int x, int k){
    int res = 1;
    while(k){
        if(k & 1) res = res * x % mod;
        x = x * x % mod;
        k >>= 1;
    }
    return res % mod;
}
int fact(int n){
    int res = 1;
    for(int i = 1; i <= n; ++i) res = res * i % mod;
    return res;
}
void eval(){
    char c = ops.top(); ops.pop();
    if(c == '!'){
        int a = num.top(); num.pop();
        num.push(f[a] % mod);      
        return ;
    }
    int b = num.top(); num.pop();
    int a = num.top(); num.pop();
    if(c == '+') num.push((a + b)%mod);
    else if(c == '-') num.push((a - b)%mod);
    else if(c == '*') num.push(a * b % mod);
    else if(c == '/') {
        if(b % mod == 0){
            cout << "ArithmeticException" << endl;
            flag = true;
            return;
        }
        num.push(a / b % mod);
    }
    else if(c == '^') num.push(ksm(a, b) % mod);

}

signed main(){
    f[0] = 1;
    for(int i = 1; i < N; ++i) f[i] = f[i-1] * i % mod;
    int t; cin >> t;
    while(t--){
        flag = false;
        string s, str; cin>>s;
        for(int i = 0; i < s.size(); ++i){
            if(s[i] >= '0' && s[i] <= '9'){
                int j = i, t = 0;
                while(s[j] >= '0' && s[j] <= '9'){t = t * 10 + s[j] - '0'; ++j;};
                num.push(t%mod);
                i = j - 1;
            }else if(s[i] == '-' && !(s[i-1] >= '0' && s[i-1] <= '9')){ //判断负数
                int j = i + 1, t = 0;
                while(s[j] >= '0' && s[j] <= '9'){t = t * 10 + s[j] - '0'; ++j;};
                num.push(-t);
                i = j - 1;
            }else{;
                while(ops.size() && mp[ops.top()] >= mp[s[i]]) eval();
                if(flag) break;
                ops.push(s[i] % mod);
            }
            if(flag) break;
        }
        while(ops.size()) eval();
        if(!flag) cout << num.top() % mod << endl;
    }
    
    return 0;
}
posted @ 2025-03-18 20:58  awei040519  阅读(10)  评论(0)    收藏  举报