Friday, February 10, 2012

Roman Number Converter - Java Program

This is a simple Java program to convert Roman numbers to Hindu-Arabic numbers. This Java method "convertRomToInt()" gets the Roman number as a string and converts it in to corresponding Integer value.
Even though this program seems simple, the algorithm is bit complex. When we convert a Roman number to Hindu-Arabic number manually, we do it in the following manner.
MCMXLIV = 1000 + (1000 − 100) + (50 − 10) + (5 − 1) = 1944
Value of each number is added together. When smaller values precede larger values, the smaller values are subtracted from the larger values, and the result is added to the total.
This algorithm use above technique to the conversion. "for" loop gets each character of the roman number string from the beginning and gets its integer value from the "getInt()"  method. At each iteration character is compared with the next character value. If the next character is the same, the value is added to mediator to add in the next iteration. If it is large, the value is added to mediator to subtract in the next iteration.