Friday, February 7, 2014

C# convert Roman Numbers to Decimal Numbers

Hi,

    Just want to share a C# code which converts Roman Numbers to Decimal Numbers. Use only valid Roman Numbers while testing (all caps and accepted sequence) and use .Net 3.5 and above.
public int RomanToNumeric(string romanNum)
{
        int[] ints = romanNum.ToCharArray().Select(x => { return x=='I' ? 1 : x=='V' ? 5 : x=='X' ? 10 : x=='L' ? 50 : x=='C' ? 100 : x=='D' ? 500 : x=='M' ? 1000 : 0; }).ToArray();
        int calc = 0;
        for(int i=0;i<ints.Length;i++)
        {
            int mult = (i+1 < ints.Length && ints[i+1] > ints[i]) ? -1 : 1;
            calc += mult*ints[i];
        }
        return calc;
}

code process:
  • convert string to char array. 
  • convert each char (roman number) to its equivalent decimal number and stores them in array. 
  • Iterating over array, check whether low number is left side next to high number if yes, remove that low number from high number else add both numbers. 
  • Assumes only one low number comes left side and max 3 low numbers right side at a time of high number. (Ex: IV & VIII) 

 Try invoking the above method with these sample Roman Numbers:
"MMXIII" -> 2013; DCCCXLI -> 841; MCMLXVII -> 1967; XIX -> 19

 Comment if you have any suggestions or alternative code.

No comments:

Post a Comment