小计算器 (蓝桥杯)
问题描述
模拟程序型计算器,依次输入指令,可能包含的指令有
1. 数字:‘NUM X’,X为一个只包含大写字母和数字的字符串,表示一个当前进制的数
2. 运算指令:‘ADD’,‘SUB’,‘MUL’,‘DIV’,‘MOD’,分别表示加减乘,除法取商,除法取余
3. 进制转换指令:‘CHANGE K’,将当前进制转换为K进制(2≤K≤36)
4. 输出指令:‘EQUAL’,以当前进制输出结果
5. 重置指令:‘CLEAR’,清除当前数字
指令按照以下规则给出:
数字,运算指令不会连续给出,进制转换指令,输出指令,重置指令有可能连续给出
运算指令后出现的第一个数字,表示参与运算的数字。且在该运算指令和该数字中间不会出现运算指令和输出指令
重置指令后出现的第一个数字,表示基础值。且在重置指令和第一个数字中间不会出现运算指令和输出指令
进制转换指令可能出现在任何地方
运算过程中中间变量均为非负整数,且小于2^63。
以大写的’A’'Z’表示1035输入格式 第1行:1个n,表示指令数量
第2…n+1行:每行给出一条指令。指令序列一定以’CLEAR’作为开始,并且满足指令规则输出格式 依次给出每一次’EQUAL’得到的结果样例输入7
CLEAR
NUM 1024
CHANGE 2
ADD
NUM 100000
CHANGE 8
EQUAL样例输出2040
C++源码
#include <cstdio>
#include <string>
#include <cstdlib>
#include <vector>
#include <iostream>
#include <cstring>
using namespace std;
typedef long long LL;
string Left,oper,Right,Hex="10";
LL hexToTen(string num){
LL HEX=atoll(Hex.c_str());
if(HEX==10) return atoll(num.c_str());
LL res=0,temp=1;
int base=0;
for(int i=num.size()-1;i>=0;--i){
char c=num[i];
if(c>='A'&&c<='Z') base=10+(c-'A');
else base=c-'0';
res+=temp*base;
temp*=HEX;
}
return res;
}
LL getResult(){
LL a=atoll(Left.c_str()),b=atoll(Right.c_str()),c=0;
if(oper=="ADD") c=a+b;
else if(oper=="SUB") c=a-b;
else if(oper=="MUL") c=a*b;
else if(oper=="DIV") c=a/b;
else if(oper=="MOD") c=a%b;
return c;
}
void hexToNow(LL result){
if(result==0){
puts("0");
return;
}
vector<char>vect;
LL t,HEX=atoll(Hex.c_str());
while(result!=0){
t=result%HEX;
if(t>=10)
vect.push_back((char)('A'+t-10));
else
vect.push_back((char)(t+'0'));
result/=HEX;
}
char res[101];
int len=0;
for(int i=vect.size()-1;i>=0;--i){
res[len++]=vect[i];
}
res[len]='\0';
puts(res);
}
void solveOper(string order,string num){
char temp[101];
if(order=="NUM"){
if(oper==""){
sprintf(temp,"%lld",hexToTen(num));
Left=string(temp);
}
else{
sprintf(temp,"%lld",hexToTen(num));
Right=string(temp);
sprintf(temp,"%lld",getResult());
Left=string(temp);
oper=Right="";
}
}
else if(order=="CHANGE"){
Hex=num;
}
else if(order=="EQUAL"){
hexToNow(atoll(Left.c_str()));
}
else if(order=="CLEAR"){
Left=oper=Right="";
}
else{
oper=order;
}
}
int main(){
int n;
char str[51];
scanf("%d",&n);
getchar();
while(n--){
fgets(str,sizeof(str),stdin);
string order(str,strlen(str)-1);
int index=order.find(' ');
if(index<0){
solveOper(order,"");
}else{
solveOper(order.substr(0,index),order.substr(index+1));
}
}
}