【简单】罗马数字转整数

https://leetcode-cn.com/problems/roman-to-integer/

能比较快想到的一个方法:

public class RomanToInt {
    public static int romanToInt(String s) {
        int ret = 0;
        Map<String,Integer> map = new HashMap<>();
        Map<String,Integer> mapCombine = 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);
        mapCombine.put("IV",4);
        mapCombine.put("IX",9);
        mapCombine.put("XL",40);
        mapCombine.put("XC",90);
        mapCombine.put("CD",400);
        mapCombine.put("CM",900);
        char[] charArr = s.toCharArray();
        int i = 0;
        if(s.length() == 1){
            ret += map.get(String.valueOf(charArr[0]));
        }else{
            while(i < s.length()){
                if((i+1) >= s.length()) {
                    ret += map.get(String.valueOf(charArr[i]));
                    break;
                }
                if(mapCombine.containsKey(String.valueOf(charArr[i]) + String.valueOf(charArr[i+1]))){
                    ret += mapCombine.get(String.valueOf(charArr[i]) + String.valueOf(charArr[i+1]));
                    i=i+2;
                 }else{
                    ret += map.get(String.valueOf(charArr[i]));
                    i++;
                }
            }
        }
        return ret;
    }
    public static void main(String[] args){
        System.out.println(romanToInt("III"));
        System.out.println(romanToInt("IV"));
        System.out.println(romanToInt("IX"));
        System.out.println(romanToInt("LVIII"));
        System.out.println(romanToInt("MCMXCIV"));
    }
}

  网上看到还有一个更直观的解法

        int ret = 0;
        Map<String,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);
        map.put("O",4);
        map.put("P",9);
        map.put("Q",40);
        map.put("R",90);
        map.put("S",400);
        map.put("T",900);
        s = s.replaceAll("IV","O");
        s = s.replaceAll("IX","P");
        s = s.replaceAll("XL","Q");
        s = s.replaceAll("XC","R");
        s = s.replaceAll("CD","S");
        s = s.replaceAll("CM","T");
        char[] charArr = s.toCharArray();
        for(char c : charArr){
            ret += map.get(String.valueOf(c));
        }
        return ret;

  

 

posted @ 2021-05-05 20:29  cstar(小乐)  阅读(80)  评论(0编辑  收藏  举报