Roman numerals to integers

前端 未结 14 937
不思量自难忘°
不思量自难忘° 2020-12-05 20:56

I have a transfer with products that unfortunately has to get matched by product name. The biggest issue here is I might get duplicate products on account of roman numbers.

14条回答
  •  不知归路
    2020-12-05 21:44

    private static HashMap romanMap = new HashMap<>() {{
        put('I', 1); put('V', 5); put('X', 10); put('L', 50); 
        put('C', 100); put('D', 500); put('M', 1000);
    }};
    
    private static int convertRomanToInt(String romanNumeral) {
        int total = 0;
        romanNumeral = romanNumeral.toUpperCase();
    
        //add every Roman numeral
        for(int i = 0; i < romanNumeral.length(); i++) {
            total += romanMap.get(romanNumeral.charAt(i));
        }
    
        //remove the Roman numerals that are followed 
        //directly by a larger Roman numeral
        for(int i = 0; i < romanNumeral.length()-1; i++) {
            if(romanMap.get(romanNumeral.charAt(i)) 
               < romanMap.get(romanNumeral.charAt(i+1))) {
               total -= 2* romanMap.get(romanNumeral.charAt(i));
            }
        }
        return total;
    }
    
    //note that the topmost solution does not solve this Roman numeral
    //but mine does
    //also note that this solution is a preference of simplicity over complexity
    public static void main(String[] args) {
        String rn = "CcLXxiV"; //274
        System.out.println("Convert " + rn + " to " + convertRomanToInt(rn));
    }
    

提交回复
热议问题