题解 | 进制转换

进制转换

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

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNextLine()) { // 注意 while 处理多个 case
            String a = in.nextLine();
            Map<String, Integer> hexMap = new HashMap<>();
            hexMap.put("A", 10);
            hexMap.put("B", 11);
            hexMap.put("C", 12);
            hexMap.put("D", 13);
            hexMap.put("E", 14);
            hexMap.put("F", 15);
            int result = 0;
            a = a.substring(2, a.length());
            for (int i = a.length(); i >= 1; i--) {
                int first = 0;
                String str = a.substring(i-1,i);
                int descIndex = a.length() - i;
                if (hexMap.containsKey(str)) {
                    first = hexMap.get(str);
                } else {
                    first = Integer.parseInt(str);
                }
                result += first * Math.pow(16, descIndex) ;
            }

            System.out.println(result);
        }
    }
}

全部评论

相关推荐

05-19 09:12
河南大学 Java
程序员小白条:怎么还用网上的经典项目,速成是很少有人去捞面试的
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务