题解 | 数制转换
数制转换
https://www.nowcoder.com/practice/8ef02ef8571b417d8c311a87861f7a03
import java.util.LinkedList;
import java.util.Scanner;
import java.util.Stack;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
while (in.hasNextInt()) { // 注意 while 处理多个 case
int a = in.nextInt();
String n = in.next();
int b = in.nextInt();
// 从右往左遍历字符串,转数值,将a进制的n转为10进制sum
int res = 0;
for (int index = 0; index < n.length(); index++) {
int currentValue = getIntegerValue(n.charAt(index));
res = res * a + currentValue;
}
// 处理结果为 0 的情况
if (res == 0) {
System.out.println(0);
continue;
}
Stack<Character> stack = new Stack<>();
while (res != 0) {//十进制转x进制
stack.push(intTochar(res % b));
res /= b;
}
while(!stack.isEmpty()){
System.out.print(stack.pop());
}
System.out.println();
}
}
public static int getIntegerValue(char c){
if(c >= '0' && c<= '9'){
return c-'0';
}else if(c >= 'A' && c<= 'F'){
return c - 'A' + 10;
}else{
return c - 'a' + 10;
}
}
public static char intTochar(int num) {
if (num > 9) {
return (char)(num - 10 + 'A');
} else {
return (char)(num + '0');
}
}
}

