[leetcode]罗马数字和阿拉伯数字相互转换

罗马转阿拉伯

public int romanToInt(String s) {
        /*
        从左到右依次根据哈希表进行加法
        如果是“CM”900这种情况就要执行+M和-C处理
         */
        if (s.length()==0) return 0;
        Map<Character,Integer> map = new HashMap<>();
        map.put('I', 1);
        map.put('V', 5);
        map.put('X', 10);
        map.put('L', 50);
        map.put('C', 100);
        map.put('D', 500);
        map.put('M', 1000);
        int res = 0;
        res+=map.get(s.charAt(0));
        for (int i = 1; i < s.length(); i++) {
            char c = s.charAt(i);
            if (map.get(s.charAt(i-1))<map.get(c))
            {
                //*2的原因是上次误加了一次
                res = res+map.get(c)-map.get(s.charAt(i-1))*2;
            }
            else res+=map.get(c);
        }
        return res;
    }

阿拉伯转罗马

public String intToRoman(int num) {
        /*
        制表,贪心,每次取最大的
         */
        String[] symbol={"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};
        int[] value=    {1000,900,500,400, 100, 90,  50, 40,  10, 9,   5,  4,   1};
        String res = "";
        for (int i = 0;num>0; i++) {
            while (num>=value[i])
            {
                num-=value[i];
                res+=symbol[i];
            }
        }
        return res;
    }
原文地址:https://www.cnblogs.com/stAr-1/p/8466092.html