Roman numerals to integers

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

    Borrowed a lot from System.Linq on this one. String implements IEnumerable, so I figured that was appropriate since we are treating it as an enumerable object anyways. Tested it against a bunch of random numbers, including 1, 3, 4, 8, 83, 99, 404, 555, 846, 927, 1999, 2420.

        public static IDictionary CharValues 
        { 
            get 
            { 
                return new Dictionary
                {{'I', 1}, {'V', 5}, {'X', 10}, {'L', 50}, {'C', 100}, {'D', 500}, {'M', 1000}};
            } 
        }
    
        public static int RomanNumeralToInteger(IEnumerable romanNumerals)
        {
            int retVal = 0;
    
            //go backwards
            for (int i = romanNumerals.Count() - 1; i >= 0; i--)
            {
                //get current character
                char c = romanNumerals.ElementAt(i);
    
                //error checking
                if (!CharValues.ContainsKey(c)) throw new InvalidRomanNumeralCharacterException(c);
    
                //determine if we are adding or subtracting
                bool op = romanNumerals.Skip(i).Any(rn => CharValues[rn] > CharValues[c]);
    
                //then do so
                retVal = op ? retVal - CharValues[c] : retVal + CharValues[c];
            }
    
            return retVal;
        }
    

提交回复
热议问题