How to convert a Roman number to an integer in VB.NET

1 Answer

0 votes
Imports System
Imports System.Collections.Generic

Module RomanToInteger

    Private ReadOnly RomanMap As New Dictionary(Of Char, Integer) From {
        {"I"c, 1},
        {"V"c, 5},
        {"X"c, 10},
        {"L"c, 50},
        {"C"c, 100},
        {"D"c, 500},
        {"M"c, 1000}
    }

    Function RomanToInt(s As String) As Integer
        Dim total As Integer = 0
        Dim prevValue As Integer = 0

        For i As Integer = s.Length - 1 To 0 Step -1
            Dim currentValue As Integer = RomanMap(s(i))
            If currentValue < prevValue Then
                total -= currentValue
            Else
                total += currentValue
            End If
            prevValue = currentValue
        Next

        Return total
    End Function

    Sub Main()
        Dim roman As String = "XCVII"
        Dim result As Integer = RomanToInt(roman)
	
        Console.WriteLine($"The integer value of {roman} is {result}")
    End Sub

End Module


'
' XCVII =
' XC+V+I+I =
' 90+5+1+1 =
' 97

	
' run:
'
' The integer value of XCVII is 97
' 

 



answered Dec 3, 2025 by avibootz
...