题解 | #进制转换#
进制转换
https://www.nowcoder.com/practice/8f3df50d2b9043208c5eed283d1d4da6
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String string = scanner.nextLine();
Map<String,Integer> map = new HashMap<>();
map.put("a",10);
map.put("b",11);
map.put("c",12);
map.put("d",13);
map.put("e",14);
map.put("f",15);
if (!string.startsWith("0x")){
System.out.println("不合法的输入");
}
if (string.length()<3){
System.out.println("不合法的输入");
}
char[] chars = string.substring(2).toCharArray();
int bit = chars.length-1;
int sum = 0;
for (char aChar : chars) {
if(map.containsKey(Character.toLowerCase(aChar))){
sum+=map.get(aChar)*Math.pow(16,bit);
bit--;
}else{
sum+=Character.getNumericValue(aChar)*Math.pow(16,bit);
bit--;
}
}
System.out.println(sum);
}
}
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String string = scanner.nextLine();
Map<String,Integer> map = new HashMap<>();
map.put("a",10);
map.put("b",11);
map.put("c",12);
map.put("d",13);
map.put("e",14);
map.put("f",15);
if (!string.startsWith("0x")){
System.out.println("不合法的输入");
}
if (string.length()<3){
System.out.println("不合法的输入");
}
char[] chars = string.substring(2).toCharArray();
int bit = chars.length-1;
int sum = 0;
for (char aChar : chars) {
if(map.containsKey(Character.toLowerCase(aChar))){
sum+=map.get(aChar)*Math.pow(16,bit);
bit--;
}else{
sum+=Character.getNumericValue(aChar)*Math.pow(16,bit);
bit--;
}
}
System.out.println(sum);
}
}