蓝桥杯国赛|小计算器

  • JAVA跑的慢,官网的测评后三个数据会超时。
  • 运算过程大致是:全部转为十进制的运算,最后输出时再从十进制转为当前进制输出。
import java.util.Scanner;

public class 小型计算器 {
	static long num = 0;
	static int flag = -1; // 辅助运算
	static int curRadix = 10; // 辅助进制转换

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		sc.nextLine();
		for (int i = 0; i < n; i++) {
			String temp = sc.nextLine();
			f(temp);
		}
	}

	private static void f(String temp) {
		if (temp.length() == 3)
			calculate(temp);
		else if (temp.equals("CLEAR"))
			num = 0;
		else if (temp.equals("EQUAL")) {
			System.out.println(Long.toString(num, curRadix).toUpperCase());
		} else if (temp.split(" ")[0].equals("CHANGE"))
			change(temp.split(" ")[1]);
		else
			cal(temp.split(" ")[1]);
	}

	private static void cal(String string) {
		Long tempNum = Long.parseLong(string, curRadix);
		if (flag == -1) {
			num = tempNum;
		} else {
			if (flag == 1)
				num += tempNum;
			else if (flag == 2)
				num -= tempNum;
			else if (flag == 3)
				num *= tempNum;
			else if (flag == 4)
				num /= tempNum;
			else
				num %= tempNum;
			flag = -1;
		}
	}

	private static void change(String temp) {
		curRadix = Integer.parseInt(temp);
	}

	private static void calculate(String temp) {
		if (temp.equals("ADD"))
			flag = 1;
		else if (temp.equals("SUB"))
			flag = 2;
		else if (temp.equals("MUL"))
			flag = 3;
		else if (temp.equals("DIV"))
			flag = 4;
		else
			flag = 5;
	}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值