题解 | #进制转换2#
进制转换2
https://www.nowcoder.com/practice/ae4b3c4a968745618d65b866002bbd32
import java.util.*;
import java.math.BigInteger;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static final int BASE_A = 65;
public static final int BASE_a = 97;
public static BigInteger parse_to_decimal(String num, String base) {
int n = num.length();
BigInteger ret = new BigInteger("0");
BigInteger basic = new BigInteger(base);
for (int i = 0; i < n; i++) {
char cur = num.charAt(i);
BigInteger factor;
if (Character.isDigit(cur)) {
factor = new BigInteger(cur + "");
} else {
factor = new BigInteger(10 + (cur - BASE_A) + "");
}
ret = ret.add(factor.multiply(basic.pow(n - i - 1)));
}
return ret;
}
public static String parse_to_NDecimal(BigInteger num, String d) {
if (num.equals(new BigInteger("0"))) return "0";
StringBuilder sb = new StringBuilder();
BigInteger base = new BigInteger(d);
while (!num.equals(new BigInteger("0"))) {
int bit = num.mod(base).intValue();
sb.append(bit > 9 ? (char)(bit - 10 + BASE_a) : bit);
num = num.divide(base);
}
return sb.reverse().toString();
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String M = in.next();
String N = in.next();
in.nextLine();
String X = in.next();
System.out.println(parse_to_NDecimal(parse_to_decimal(X, M), N));
}
}
查看24道真题和解析