// Online C++ compiler to run C++ program online
#include<iostream>
#include<vector>
#include<stdlib.h>
#include<algorithm>
#include<iomanip>
#include<string.h>
#include<exception>
#include<map>
#include<cmath>
#include<unordered_map>
#include<set>
#include<climits>
#include<ctype.h>
#include<queue>
#include<stack>
#include<string>
#include<vector>
using namespace std;
#define TYPE_OP 1
#define TYPE_VAL 2
struct Word
{
Word(int _type, string _token)
{
type = _type;
token = _token;
}
int type = 0;
string token;
};
void scan(string str, list<Word>& opList) {
for (uint32_t i = 0; i < str.size(); ) {
for (; (str[i] == ' ' || str[i] == '\t'); ++i) continue;
if (str[i] == '(' || str[i] == ')') {
++i;
continue;
}
for (; (str[i] == ' ' || str[i] == '\t'); ++i) continue;
char ch[128] = { 0 };
int k = 0;
for ( ; str[i] >= 'a' && str[i] <= 'w'; k++, i++) {
ch[k] = str[i];
}
ch[k] = '\0';
opList.push_back(Word(TYPE_OP, string(ch)));
for (; (str[i] == ' ' || str[i] == '\t'); ++i) continue;
if (str[i] == '(') {
++i;
continue;
}
k = 0;
for (; (str[i] >= '0' && str[i] <= '9') || (str[i] == '-'); k++, i++) {
ch[k] = str[i];
}
ch[k] = '\0';
opList.push_back(Word(TYPE_VAL, string(ch)));
for (; (str[i] == ' ' || str[i] == '\t'); ++i) continue;
k = 0;
for (; (str[i] >= '0' && str[i] <= '9') || (str[i] == '-'); k++, i++) {
ch[k] = str[i];
}
ch[k] = '\0';
opList.push_back(Word(TYPE_VAL, string(ch)));
}
}
int cal(list<Word>& opList) {
int val = 0;
Word op = opList.front();
opList.pop_front();
int a, b;
if (opList.front().type == TYPE_OP)
{
a = cal(opList);
}
else
{
a = atoi(opList.front().token.c_str());
opList.pop_front();
}
if (opList.front().type == TYPE_OP)
{
b = cal(opList);
}
else
{
b = atoi(opList.front().token.c_str());
opList.pop_front();
}
if (op.token == "add") {
val = a + b;
}
else if (op.token == "sub") {
val = a - b;
}
else if (op.token == "mul") {
val = a * b;
}
else {
if (b == 0) {
cout << "error" << endl;
exit(0);
}
val = a / b;
}
return val;
}
int main() {
string str;
list<Word> opList;
getline(cin, str);
scan(str, opList);
int val = cal(opList);
cout << val << endl;
return 0;
}
华为OD机试-仿LISP运算
最新推荐文章于 2024-10-16 10:13:45 发布