How to convert a Roman number to an integer in C#

1 Answer

0 votes
using System;
using System.Collections.Generic;

public class RomanToInteger
{
    private static readonly Dictionary<char, int> RomanMap = new Dictionary<char, int> {
        { 'I', 1 },
        { 'V', 5 },
        { 'X', 10 },
        { 'L', 50 },
        { 'C', 100 },
        { 'D', 500 },
        { 'M', 1000 }
    };

    public static int RomanToInt(string s) {
        int total = 0;
        int prevValue = 0;

        for (int i = s.Length - 1; i >= 0; i--) {
            int currentValue = RomanMap[s[i]];
            if (currentValue < prevValue) {
                total -= currentValue;
            }
            else {
                total += currentValue;
            }
            prevValue = currentValue;
        }

        return total;
    }

    public static void Main()
    {
        string roman = "XCVII";
        int result = RomanToInt(roman);
        
        Console.WriteLine($"The integer value of {roman} is {result}");
    }
}


/*
XCVII =
XC+V+I+I =
90+5+1+1 =
97
*/


/*
run:

The integer value of XCVII is 97

*/

 



answered Dec 3, 2025 by avibootz
...