【Java】蓝桥杯PREV-55 小计算器
作者:互联网
一、题目描述
二、代码
import java.math.BigInteger;
import java.util.Scanner;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) {
@SuppressWarnings("resource")
Scanner in = new Scanner(System.in);
int n = in.nextInt();
String command;
BigInteger res = null;
boolean isStart = false;
int ope = 0;
int PN = 10;
in.nextLine();
for(int i = 0; i < n; i++){
StringTokenizer stringTokenizer = new StringTokenizer(in.nextLine());
command = stringTokenizer.nextToken();
if(command.equals("CHANGE")){
String str = stringTokenizer.nextToken();
PN = Integer.parseInt(str);
}
else if(command.equals("EQUAL")){
String string = res.toString(PN).toUpperCase();
System.out.println(string);
}
else if(command.equals("NUM")){
String str = stringTokenizer.nextToken();
String num = Long.valueOf(str, PN).toString();
if(isStart == true){
res = new BigInteger(num);
isStart =false;
}
else{
switch (ope) {
case 1:
res = res.add(new BigInteger(num));
break;
case 2:
res = res.subtract(new BigInteger(num));
break;
case 3:
res = res.divide(new BigInteger(num));
break;
case 4:
res = res.multiply(new BigInteger(num));
break;
case 5:
res = res.mod(new BigInteger(num));
break;
default:
break;
}
}
}
else if(command.equals("ADD")){
ope = 1;
}
else if(command.equals("SUB")){
ope = 2;
}
else if(command.equals("DIV")){
ope = 3;
}
else if(command.equals("MUL")){
ope = 4;
}
else if(command.equals("MOD")){
ope = 5;
}
else if(command.equals("CLEAR")){
res = new BigInteger("0");
isStart = true;
}
}
}
}
三、思路记录
- 读入指令,根据指令再执行后续操作
- 读入时使用 StringTokenizer 类处理一行有多个输入值的情况
StringTokenizer stringTokenizer = new StringTokenizer(in.nextLine()); command = stringTokenizer.nextToken();
- 其中读入时将 “NUM” 全部转换为十进制存储,即直接使用十进制运算,输出时再转换为要求的进制
- 使用一个变量(此处是ope)记录当前运算方式(如加减乘除等),在 “NUM” 指令中使用switch...case...根据 ope 的值执行相应运算
- 将运算结果(此处是res)的数据类型定义为BigInteger,这个类处理大数是真的方便。常用操作可参考:https://blog.csdn.net/qq_36628940/article/details/80270949(当然JDK最好用)
四、结果
有缺陷,但我不会修改了。
标签:BigInteger,55,res,equals,蓝桥,ope,command,new,PREV 来源: https://blog.csdn.net/clevercaiquebrightme/article/details/86677595