Description
As we already know, base64 is a common binary-to-text encoding scheme. Here we define a special series of positional systems that represent numbers using a base (a.k.a. radix) of 2 to 62. The symbols '0' -- '9' represent zero to nine, and 'A' -- 'Z' represent ten to thirty-five, and 'a' -- 'z' represent thirty-six to sixty-one. Now you need to convert some integer z in base x into base y.
Input
The input contains three integers x,y (2≤x,y≤62) and z (), where the integer z is given in base x.
Output
Output the integer z in base y.
样例输入
16 2 FB
样例输出
11111011
题目大意:
2-62进制间的进制转换。
分析:
大数用C++写很麻烦,这里贴一个Java的大数进制转换。
具体解释见代码。
import java.math.BigInteger;
import java.util.Stack;
import java.util.Scanner;
public class Main {
// 理论上支持62进制的转换, 当然可以自己添加一些其他符号来增加进制数
private static final String TARGET_STR = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
private static final char[] chs = TARGET_STR.toCharArray();
private static final BigInteger INTEGER0 = new BigInteger("0");
/**
* 10进制转任意进制
*/
public static String numToRadix(String number, int radix) {
if(radix < 0 || radix > TARGET_STR.length()){
radix = TARGET_STR.length();
}
BigInteger bigNumber = new BigInteger(number);
BigInteger bigRadix = new BigInteger(radix + "");
Stack<Character> stack = new Stack<>();
StringBuilder result = new StringBuilder(0);
while (!bigNumber.equals(INTEGER0)) {
stack.add(chs[bigNumber.remainder(bigRadix).intValue()]);
bigNumber = bigNumber.divide(bigRadix);
}
for (; !stack.isEmpty(); ) {
result.append(stack.pop());
}
return result.length() == 0 ? "0" : result.toString();
}
/**
* 任意进制转10进制
*/
public static String radixToNum(String number, int radix){
if(radix < 0 || radix > TARGET_STR.length()){
radix = TARGET_STR.length();
}
if (radix == 10) {
return number;
}
char ch[] = number.toCharArray();
int len = ch.length;
BigInteger bigRadix = new BigInteger(radix + "");
BigInteger result = new BigInteger("0");
BigInteger base = new BigInteger("1");
for (int i = len - 1; i >= 0; i--) {
BigInteger index = new BigInteger(TARGET_STR.indexOf(ch[i]) + "");
result = result.add(index.multiply(base)) ;
base = base.multiply(bigRadix);
}
return result.toString();
}
/**
* 任意进制之间的互相转换, 先将任意进制转为10进制, 然后在转换为任意进制
*/
public static String transRadix(String num, int fromRadix, int toRadix) {
return numToRadix(radixToNum(num, fromRadix), toRadix);
}
public static void main(String[] args) {
Scanner cin = new Scanner(System.in);
int x = cin.nextInt();
int y = cin.nextInt();
String s = cin.next();
System.out.println(Main.transRadix(s, x, y));
}
}