题解 | HJ5 进制转换
进制转换
https://www.nowcoder.com/practice/8f3df50d2b9043208c5eed283d1d4da6?tpId=37&tqId=21228&rp=1&sourceUrl=%2Fexam%2Foj%2Fta%3Fpage%3D1%26pageSize%3D50%26search%3D%26tpId%3D37%26type%3D37&difficulty=undefined&judgeStatus=undefined&tags=&title=
import java.util.Scanner;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String s = in.nextLine(); // 读取十六进制字符串,如 "0xAA"
int sum = 0; // 累加最终的十进制结果
int cnt = 0; // 当前位的幂次(0, 1, 2...)
// 从字符串末尾向前遍历,跳过前两位 "0x"
for (int i = s.length() - 1; i >= 2; i--) {
char c = s.charAt(i); // 获取当前字符
// 字母字符(A-F)转成 10-15,数字字符转成 0-9
if (Character.isLetter(c)) {
sum += (c - 'A' + 10) * Math.pow(16, cnt);
} else {
sum += (c - '0') * Math.pow(16, cnt);
}
cnt++; // 幂次加1(从低位到高位)
}
System.out.println(sum);
}
}
查看23道真题和解析