Skip to content

Instantly share code, notes, and snippets.

@asahicantu
Created September 19, 2024 07:45
Show Gist options
  • Save asahicantu/eb84dd12335d00a5770c131114141949 to your computer and use it in GitHub Desktop.
Save asahicantu/eb84dd12335d00a5770c131114141949 to your computer and use it in GitHub Desktop.
Roman to int C# Program
/*
* C# Program to Convert Roman to Arabic Numerals
*/
static int RomanToInt(int decimalNumber, int i, string romanString)
{
var romanChar = TryGetCharAt(romanString, i);
return romanChar switch
{
'I' when TryGetCharAt(romanString, i + 1) == 'V' => RomanToInt(decimalNumber + 4, i + 2, romanString),
'I' => RomanToInt(decimalNumber + 1, ++i, romanString),
'V' => RomanToInt(decimalNumber + 5, ++i, romanString),
'X' when TryGetCharAt(romanString, i + 1) == 'L' => RomanToInt(decimalNumber + 40, i + 2, romanString),
'X' => RomanToInt(decimalNumber + 10, ++i, romanString),
'L' => RomanToInt(decimalNumber + 50, ++i, romanString),
'C' when TryGetCharAt(romanString, i + 1) == 'D' => RomanToInt(decimalNumber + 400, i + 2, romanString),
'C' when TryGetCharAt(romanString, i + 1) == 'M' => RomanToInt(decimalNumber + 900, i + 2, romanString),
'C' => RomanToInt(decimalNumber + 100, ++i, romanString),
'D' => RomanToInt(decimalNumber + 500, ++i, romanString),
'M' => RomanToInt(decimalNumber + 1000, ++i, romanString),
_ => decimalNumber,
};
}
static char TryGetCharAt(string romanString, int i)
{
return i < romanString.Length ? romanString[i] : ' ';
}
var romanString = args[0].ToUpper();
var romanConverted = RomanToInt(0, 0, romanString);
Console.WriteLine($"Roman Number : {romanString} = {romanConverted}");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment