题目描述
写出一个程序,接受一个十六进制的数,输出该数值的十进制表示。(多组同时输入 )
思路1:直接调用方法parseInt(String s,int radix),“int radix”进制数。
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
String str=sc.nextLine();
System.out.println(Integer.parseInt(str.substring(2),16));
}
}
}
排坑;由于输入的是16进制,有0x,因此字符串需要从2开始计算。
思路2:因为有0x存在,因此先建立字符数组ch1将0x排除。再遍历,因为都是asc码值,因此如果是大写字母就减去55,如果是数字就减去48。
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int sum = 0;
while (sc.hasNext()) {
String str = sc.nextLine();
char ch[] = str.toCharArray();
char ch1[] = new char[ch.length - 2];
for (int i = 0; i < ch1.length; i++) {
ch1[i] = ch[i + 2];
}
for (int i = 0; i < ch1.length; i++) {
if (ch1[i] >= 65 && ch1[i] <= 90) {
sum += Math.pow(16, ch1.length - i-1) * (ch1[i] - 65 + 10);
} else {
sum += Math.pow(16, ch1.length - i-1) * (ch1[i]-48);
}
}
System.out.println(sum);
sum = 0;
}
}
}