Code Explanation

I began getting requests from students for the source code to my Arabic to Roman numeral converter not too long after I put it on the Internet. I'm a firm believer in students doing their own work, so I will not give the source to anyone. (Besides, it's written in Perl, which allows me to do some things not easily done in C.) It has nothing to do with planning on making money from such a simple algorithm. Although I won't give out the source, here's a brief and purposely vague explanation of how it works:

I start with an array of the Roman numeral "digits". (Perl is great for manipulating text by breaking each character of a string into an array and such.) Then I determine the length of the input (decimal) number. This tells me where in the array to set my pointers for ones, fives, and tens. After this is set up, I just iterate through each digit with a big if-else statement (Perl doesn't have a case statement.) for each digit 1-9 (zeroes are meaningless in Roman numerals), building my string.

Here's an exmple of the steps for "14":

  1. length(Input) = 2, so One="X", Five="L", Ten="C"
  2. if (1 == Input) . . . yep!
  3. String = String + One
  4. Remaining digits in Input, so now One="I", Five="V", Ten="X"
  5. if (1 == Input) . . . nope!
  6. else if (2 == Input) . . . nope!
  7. else if (3 == Input) . . . nope!
  8. else if (4 == Input) . . . yep!
  9. String = String + One + Five
  10. No more digits in Input, return String ("XIV")

Since I wrote the converter, I've come up with a slightly better way of doing it involving two arrays of Roman numeral "digits" instead of one. This is left as an exercise for the reader. 8) Also, Paul Pearson, a friend of mine, independently came up with something better than nine else/if statements. This, also, is left as an excercise for the reader. 8)

I have not implemented either alternative into my converter and probably never will since what I have works. Sometime after the creation of my coverter, a standard Perl module for handling Roman numerals was created. So, if anything, I'd just go with that now.


Jump to:


Return to Lee's Useless Roman Numeral Converter.
Written by: Lee K. Seitz (lkseitz@hiwaay.net)
Created: 28 Feb 1996; Last Modified: 9 Jun 2004