k进制转十进制
import java.util.Scanner;
public class Main {
public static int cal(char c) {
if (c >= 'A')//字符是字母
return 10 + c - 'A';
return c - '0';//字符是数字
}
//将给定字符串 s 转化为十进制数, k 是目标进制
public static int change(int k,String s) {
int ans = 0;//初始值
//正序模板(从高到低)
for (int i = 0;i < s.length();i ++)
ans = ans * k + cal(s.charAt(i));
return ans;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.next();
System.out.print(change(16,s));
}
}
十进制转k进制
import java.util.Scanner;
public class Main {
public static String change(int x,int k) {
StringBuilder ans = new StringBuilder();
while (x != 0) {
int t = x % k;//余数作为当前位的数
if (t <= 9)
ans.append((char)('0'+ t));
else
ans.append((char)('A' + t - 10));
x /= k;//更新x,商用于下一次迭代
}
return ans.reverse().toString();
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int s = sc.nextInt();
System.out.print(change(s,16));
}
}