Mega Code Archive

 
Categories / Delphi / Ide Indy
 

Delphi Roman to Integer Convert Roman Numbers to Arabic Integer Numbers using Delphi

Title: Delphi Roman to Integer - Convert Roman Numbers to Arabic / Integer Numbers using Delphi The number system in most common use today is the Arabic system. The ten single-digit numerals, "0" through "9", make up the symbols of our numbering system. An example of a different numeral system is the system of Roman numerals, which could represent all the numbers from 1 to 1,000,000 using only seven symbols: I = 1, V = 5, X = 10, L = 50, C = 100, D = 500, M = 1000. Example: 1973 (Arabic) is MCMLXXIII (Roman). Delphi MMIIX Converting from 2009 to MMIX is easy, an algorithm is provided in How to convert numbers from one base to another. How to convert a roman number to its arabic representation? Here's a Delphi function that does the job: function RomanToArabic(const romanNumber : string) : integer ; const romanChars = 'IVXLCDMvxlcdm?!#' ; decades : array [0..8] of integer = (0, 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000) ; OneFive : array [boolean] of byte = (1, 5) ; var newValue, oldValue : integer ; cIdx, P : byte ; begin result := 0; oldValue := 0 ; for cIdx := Length(romanNumber) downto 1 do begin P := Succ(Pos(romanNumber[cIdx], romanChars)) ; newValue := OneFive[Odd(P)] * decades[P div 2] ; if newValue = 0 then begin result := -1; Exit; end ; if newValue then newValue := - newValue ; Inc(result, newValue) ; oldValue := newValue end ; end; Note: RomanToArabic would return -1 if the "romanNumber" parameter is *not* a roman number (for example "MIXKIX" is not a roman number). If Douglas Adams was in Rome at the time of writing his Guide, the definitive answer would probably be XLII ;)