2019 ICPC Asia Yinchuan Regional I. Base62

2019 ICPC Asia Yinchuan Regional I. Base62

【题目大意】
将x进制下的z转换成y进制

【解题思路】
由于数据很大,考虑用Java大数模拟

【AC代码】

import java.util.*;
import java.math.*;
class Main {
	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);
		int x = input.nextInt();
		int y = input.nextInt();
		String s = input.next();
		if(x == y || s == "0") {
			System.out.println(s);
		}
		else if(x <= 36 && y <= 36) {
			System.out.println(new BigInteger(s, x).toString(y).toUpperCase());
		}
		else if(x <= 36) {
			BigInteger z = new BigInteger(new BigInteger(s, x).toString(10));
			char[] ans = new char[300];
			int len = 300;
			while(z.compareTo(BigInteger.valueOf(0)) > 0) {
				int c = z.mod(BigInteger.valueOf(y)).intValue();
				z = z.divide(BigInteger.valueOf(y));
				if(c < 10) {
					ans[--len] = (char)(c + '0');
				}
				else if(c <= 35) {
					ans[--len] = (char)(c + 'A' - 10);
				}
				else {
					ans[--len] = (char)(c + 'a' - 36);
				}
			}
			for(int i = len; i <= 299; ++i) {
				System.out.print(ans[i]);
			}
			System.out.println();
		}
		else {
			char[] cc = s.toCharArray();
			BigInteger z = new BigInteger("0");
			int l = s.length();
			for(int i = l - 1; i >= 0; --i) {
				int t = 0;
				if(cc[i] >= '0' && cc[i] <= '9') {
					t = cc[i] - '0';
				}
				else if(cc[i] >= 'A' && cc[i] <= 'Z') {
					t = cc[i] - 'A' + 10;
				}
				else {
					t = cc[i] - 'a' + 36;
				}
				z = z.add(BigInteger.valueOf(x).pow(l - i - 1).multiply(BigInteger.valueOf(t)));
			}
			if(y <= 36) {
				System.out.println(z.toString(y).toUpperCase());
			}
			else {
				char[] ans = new char[300];
				int len = 300;
				while(z.compareTo(BigInteger.valueOf(0)) > 0) {
					int c = z.mod(BigInteger.valueOf(y)).intValue();
					z = z.divide(BigInteger.valueOf(y));
					if(c < 10) {
						ans[--len] = (char)(c + '0');
					}
					else if(c <= 35) {
						ans[--len] = (char)(c + 'A' - 10);
					}
					else {
						ans[--len] = (char)(c + 'a' - 36);
					}
				}
				for(int i = len; i <= 299; ++i) {
					System.out.print(ans[i]);
				}
				System.out.println();
			}
		}
		input.close();
	}
}

你可能感兴趣的:(ICPC)