2020杭电多校第六场 1002 Little Rabbit‘s Equation

题目

2020杭电多校第六场 1002 Little Rabbit‘s Equation_第1张图片
题目大意就是给定T组数据,每组数据一个等式,等式包含一个单次四则运算,问给定等式在几进制下合法,不合法就输出-1.

简单模拟

这个题目直接模拟即可,进制最大只到16,所以暴力枚举每一种进制不会有任何问题。需要注意的是,最小的可能应该是所有数字字符中最大值+1,例如12+23=56中最大的字符为6,则其中最小可能进制为6,应该从6开始枚举。

除此以外需要注意的就是爆int问题,题目中提到等式长度不超过15位所以直接使用long long即可

由于java包装类处理字符串转指定进制较为方便,这个题目就是用java了

import java.util.Scanner;

public class Main {
	static String as,bs,cs;
	static char sign;
	
	
	static boolean  check(int redix) {
		long a = Long.parseLong(as,redix);
		long b = Long.parseLong(bs,redix);
		long c = Long.parseLong(cs,redix);
		switch(sign) {
			case '+':return a + b == c;
			case '-':return a - b == c;
			case '*':return a * b == c;
			case '/':return a % b != 0 ? false : a / b == c;
		}
		return false;
	}
	public static void main(String[] str) {
		
		Scanner scan = new Scanner(System.in);
		String equation;
		int mi;
		while(scan.hasNext()) {
			equation = scan.next();
			parse(equation);
			mi = 1;
			mi = Math.max(mi, getMi(as));
			mi = Math.max(mi, getMi(bs));
			mi = Math.max(mi, getMi(cs));
			
			for(int i = mi + 1;i <= 16;i++) {
				if(check(i)) {
					System.out.println(i);
					break;
				}
				if(i == 16) {
					System.out.println(-1);
				}
			}
		}
	}
	private static int getMi(String s) {
		int mi = 1;
		char[] c = s.toCharArray();
		for(int i = 0;i < c.length;i++) {
			if(c[i] >= '0' && c[i] <= '9') {
				mi = Math.max(mi,c[i] - '0');
			}else {
				mi = Math.max(mi, c[i] - 'A' + 10);
			}
		}
		return mi;
	}
	private static void parse(String equation) {
		cs = equation.split("=")[1];
		equation = equation.split("=")[0];
		
		if(equation.indexOf('+') != -1){
			as = equation.substring(0,equation.indexOf('+'));
			bs = equation.substring(equation.indexOf('+') + 1,equation.length());
			sign = '+';
		}else if(equation.indexOf('-') != -1){
			as = equation.substring(0,equation.indexOf('-'));
			bs = equation.substring(equation.indexOf('-') + 1,equation.length());
			sign = '-';
		}else if(equation.indexOf('*') != -1) {
			as = equation.substring(0,equation.indexOf('*'));
			bs = equation.substring(equation.indexOf('*') + 1,equation.length());
			sign = '*';
		}else if(equation.indexOf('/') != -1) {
			as = equation.substring(0,equation.indexOf('/'));
			bs = equation.substring(equation.indexOf('/') + 1,equation.length());
			sign = '/';
		}
	//	System.out.println(as + " " + bs + " " + cs);
	}
}

你可能感兴趣的:(#,杭电多校,字符串,java)