描述
写出一个程序,接受一个十六进制的数,输出该数值的十进制表示
输入描述
输入一个十六进制的数值字符串。注意:一个用例会同时有多组输入数据,请参考帖子https://www.nowcoder.com/discuss/276处理多组输入的问题。
输出描述
输出该数值的十进制字符串。不同组的测试用例用\n隔开
示例1
输入:
0xA
0xAA
复制
输出:
10
170
题解1
运行时间29ms 占用内存10584KB
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
while (sc.hasNext()){
String temp = sc.next().replaceAll("x","");
System.out.println(Integer.parseInt(temp,16));
}
}
}
题解2
运行时间37ms 占用内存10708KB
import java.util.*;
public class Main
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
while(scanner.hasNext())
{
String str = scanner.nextLine();
System.out.println(Integer.valueOf(str.substring(2),16).toString());
}
}
}
题解3
import java.util.*;
public class Main {
private final int BASE = 16;
private Map<Character, Integer> map;
public Main() {
map = new HashMap();
map.put('0', 0);
map.put('1', 1);
map.put('2', 2);
map.put('3', 3);
map.put('4', 4);
map.put('5', 5);
map.put('6', 6);
map.put('7', 7);
map.put('8', 8);
map.put('9', 9);
map.put('A', 10);
map.put('B', 11);
map.put('C', 12);
map.put('D', 13);
map.put('E', 14);
map.put('F', 15);
}
public int getDecimal(String number) {
int res = 0;
for (char ch : number.toCharArray()) {
res = res * BASE + map.get(ch);
}
return res;
}
public static void main(String[] args) {
Main solution = new Main();
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
String number = in.next();
int res = solution.getDecimal(number.substring(2));
System.out.println(res);
}
}
}
反思
String的replaceAll() parseInt(String s, int radix) parseInt(CharSequence s, int beginIndex, int endIndex, int radix) parseInt(String s) String.subString() Integer.valueof()
|