Skip to content

Instantly share code, notes, and snippets.

@ChinonsoIke
Last active November 9, 2022 15:33
Show Gist options
  • Save ChinonsoIke/4ca3900d30a84d0d456095fc51ee1170 to your computer and use it in GitHub Desktop.
Save ChinonsoIke/4ca3900d30a84d0d456095fc51ee1170 to your computer and use it in GitHub Desktop.
This algorithm converts Roman numerals to a numeric decimal integer
using System.Collections.Generic;
public class RomanToInt
{
public static int Decode(string roman)
{
var dict = new Dictionary<char,int>(){
{'M',1000},
{'D',500},
{'C',100},
{'L',50},
{'X',10},
{'V',5},
{'I',1}
};
int num = 0;
for(int i=0; i<roman.Length; i++){
// iv, ix, xl, xc, cd,cm
switch(roman[i]){
case 'I':
if(i < roman.Length-1){
if(roman[i+1] == 'V') {
num += 4;
i++;
break;
}
if(roman[i+1] == 'X') {
num += 9;
i++;
break;
}
}
num += dict[roman[i]];
break;
case 'X':
if(i < roman.Length-1){
if(roman[i+1] == 'L') {
num += 40;
i++;
break;
}
if(roman[i+1] == 'C') {
num += 90;
i++;
break;
}
}
num += dict[roman[i]];
break;
case 'C':
if(i < roman.Length-1){
if(roman[i+1] == 'D') {
num += 400;
i++;
break;
}
if(roman[i+1] == 'M') {
num += 900;
i++;
break;
}
}
num += dict[roman[i]];
break;
default:
num += dict[roman[i]];
break;
}
}
return num;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment