专注于 JetBrains IDEA 全家桶,永久激活,教程
持续更新 PyCharm,IDEA,WebStorm,PhpStorm,DataGrip,RubyMine,CLion,AppCode 永久激活教程

LeetCode 12. 整数转罗马数字

leetcode-cn.com/problems/in…

81_1.png

思路:做映射,特殊情况也做映射,遍历号数的每一位,对于每一位做判断

public String intToRoman(int num) {
    // 映射
    Map<Integer, String> map = new HashMap<>();
    map.put(1, "I");
    map.put(5, "V");
    map.put(10, "X");
    map.put(50, "L");
    map.put(100, "C");
    map.put(500, "D");
    map.put(1000, "M");
    // 特殊情况映射
    map.put(4, "IV");
    map.put(9, "IX");
    map.put(40, "XL");
    map.put(90, "XC");
    map.put(400, "CD");
    map.put(900, "CM");

    String roman = "";
    int a = num;
    int b = 0;
    int nTen = 1;
    while (a > 0 || b > 0) {
        b = a % 10;
        a = a / 10;
        int key = nTen * b;
        if (b == 0) {
            // 对应0的情况
        } else if (map.get(key) == null) {
            if (b == 2 || b == 3) {
                // 对应2,3情况
                for (int i = 0; i < b; i++) {
                    roman = map.get(nTen) + roman;
                }
            } else {
                // 对应6,7,8
                for (int i = 0; i < b - 5; i++) {
                    roman = map.get(nTen) + roman;
                }
                roman = map.get(5 * nTen) + roman;
            }
        } else {
            // 对应1,4,9的情况
            roman = map.get(key) + roman;
        }
        nTen *= 10;
    }
    return roman;
}

文章永久链接:https://tech.souyunku.com/43453

未经允许不得转载:搜云库技术团队 » LeetCode 12. 整数转罗马数字

JetBrains 全家桶,激活、破解、教程

提供 JetBrains 全家桶激活码、注册码、破解补丁下载及详细激活教程,支持 IntelliJ IDEA、PyCharm、WebStorm 等工具的永久激活。无论是破解教程,还是最新激活码,均可免费获得,帮助开发者解决常见激活问题,确保轻松破解并快速使用 JetBrains 软件。获取免费的破解补丁和激活码,快速解决激活难题,全面覆盖 2024/2025 版本!

联系我们联系我们