Roman numerals to integers

前端 未结 14 946
不思量自难忘°
不思量自难忘° 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:32

    I wrote a simple Roman Numeral Converter just now, but it doesn't do a whole lot of error checking, but it seems to work for everything I could throw at it that is properly formatted.

    public class RomanNumber
    {
        public string Numeral { get; set; }
        public int Value { get; set; }
        public int Hierarchy { get; set; }
    }
    
    public List RomanNumbers = new List
        {
            new RomanNumber {Numeral = "M", Value = 1000, Hierarchy = 4},
            //{"CM", 900},
            new RomanNumber {Numeral = "D", Value = 500, Hierarchy = 4},
            //{"CD", 400},
            new RomanNumber {Numeral = "C", Value = 100, Hierarchy = 3},
            //{"XC", 90},
            new RomanNumber {Numeral = "L", Value = 50, Hierarchy = 3},
            //{"XL", 40},
            new RomanNumber {Numeral = "X", Value = 10, Hierarchy = 2},
            //{"IX", 9},
            new RomanNumber {Numeral = "V", Value = 5, Hierarchy = 2},
            //{"IV", 4},
            new RomanNumber {Numeral = "I", Value = 1, Hierarchy = 1}
        };
    
    /// 
    /// Converts the roman numeral to int, assumption roman numeral is properly formatted.
    /// 
    /// The roman numeral string.
    /// 
    private int ConvertRomanNumeralToInt(string romanNumeralString)
    {
        if (romanNumeralString == null) return int.MinValue;
    
        var total = 0;
        for (var i = 0; i < romanNumeralString.Length; i++)
        {
            // get current value
            var current = romanNumeralString[i].ToString();
            var curRomanNum = RomanNumbers.First(rn => rn.Numeral.ToUpper() == current.ToUpper());
    
            // last number just add the value and exit
            if (i + 1 == romanNumeralString.Length)
            {
                total += curRomanNum.Value;
                break;
            } 
    
            // check for exceptions IV, IX, XL, XC etc
            var next = romanNumeralString[i + 1].ToString();
            var nextRomanNum = RomanNumbers.First(rn => rn.Numeral.ToUpper() == next.ToUpper());
    
            // exception found
            if (curRomanNum.Hierarchy == (nextRomanNum.Hierarchy - 1))
            {
                total += nextRomanNum.Value - curRomanNum.Value;
                i++;
            }
            else
            {
                total += curRomanNum.Value;
            }
        }
    
    
        return total;
    }
    

提交回复
热议问题