题解 | #质数因子#

进制转换

http://www.nowcoder.com/practice/8f3df50d2b9043208c5eed283d1d4da6

先声明一个静态常量BASE private static final int BASE=16;

为了提高性能,将字符对应的十进制存入map中, 将输入的十六进制取出前面的"0x"后作为数值 num, 遍历获取的数值,将其转为char数组, 再采用map获取每个char对应的值: private static Map<Character, Integer> map = new HashMap<Character, Integer>() { { put('0', 0); put('1', 1); put('2', 2); put('3', 3); put('4', 4); put('5', 5); put('6', 6); put('7', 7); put('8', 8); put('9', 9); put('A', 10); put('B', 11); put('C', 12); put('D', 13); put('E', 14); put('F', 15); put('a', 10); put('b', 11); put('c', 12); put('d', 13); put('e', 14); put('f', 15); } };

public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);
    while (sc.hasNext()) {
        String hex = sc.next();
        String num = hex.substring(2);
        int rs = 0;
        for (char ch : num.toCharArray()) {
            rs = rs * BASE + map.get(ch);
        }
        System.out.println(rs);
    }
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务