You can find algorithms for creating Roman Numerals from decimal values here and here.
In this post we'll take a look at the first of two algorithms for accepting a Roman Numeral and converting it back into a decimal value.
The basic rules for this algorithms are:
Start at the left-most character in the Roman Numeral string and work your way to the last character one character at a time. Add the value of the current character to the total. If the current character has a larger value than the previous character, then subtract 2x the value of the previous character from the total.
For instance the Roman Numeral XIX has a decimal value of 19. We start at the first character, 'X', and add 10 to the running total; our total is now 10. We evaluate the second character, 'I' and add 1 to our running total, which now becomes 11. We evaluate the third character, 'X', and add 10 to our total; our total is now 21, but... Because the current character has a larger value than the previous character we must subtract 2x the value of the previous character, 1, from the total bringing the new total to 19. There are no more characters so we stop.
Function Roman2Decimal(strInput as string) as integer
Dim intValues() as integer ' Reserve space for an array.
Dim intLoopI as integer = nothing ' Initialize the loop counter to 0.
Dim intTotal as integer = nothing ' Clear the total.
Dim intPreviousPointer as integer = 99999 ' Set the value of the previous pointer to some MAX value.
Dim intCurrentPointer as integer = nothing ' This will hold the value of the current Roman Numeral character.
intValues(M) = 1000 ' This array addressing method
intValues(D) = 500 ' assumes that the language you
intValues(C) = 100 ' are using allows you to use
intValues(L) = 50 ' values other than integer values
intValues(X) = 10 ' to access data in an array.
intValues(V) = 5
intValues(I) = 1
For intLoopI = 0 to (len(strInput)-1) ' Assuming 0 indexing...
intCurrentPointer = intValues(mid$(strInput,intLoopI,1)) ' Get the value of the current Roman Numeral character
intTotal = intTotal + intCurrentPointer ' Add the value to the total.
If intCurrentPointer > intPreviousPointer then ' If the current value is larger than the previous, then
intTotal = intTotal - (2 * intPreviousPointer) ' subtract twice the value of the previous character from the total.
EndIf
intPreviousPointer = intCurrentPointer ' Move the value of the current character to be the
' value of the previous character and get then next one.
Next
Roman2Decimal = intTotal
End Function
No comments:
Post a Comment