Roman numerals to integers

前端 未结 14 890
不思量自难忘°
不思量自难忘° 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<Character, Integer> 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));
    }
    
    0 讨论(0)
  • 2020-12-05 21:44
    public static int ConvertRomanNumtoInt(string strRomanValue)
    {
        Dictionary RomanNumbers = new Dictionary
        {
            {"M", 1000},
            {"CM", 900},
            {"D", 500},
            {"CD", 400},
            {"C", 100},
            {"XC", 90},
            {"L", 50},
            {"XL", 40},
            {"X", 10},
            {"IX", 9},
            {"V", 5},
            {"IV", 4},
            {"I", 1}
        };
        int retVal = 0;
        foreach (KeyValuePair pair in RomanNumbers)
        {
            while (strRomanValue.IndexOf(pair.Key.ToString()) == 0)
            {
                retVal += int.Parse(pair.Value.ToString());
                strRomanValue = strRomanValue.Substring(pair.Key.ToString().Length);
            }
        }
        return retVal;
    }
    
    0 讨论(0)
提交回复
热议问题