Java Convert Integer to Roman Numbers

Roman Number

Roman numerals have seven symbols. The table below shows these symbols and their decimal equivalents.

SymbolNumber
I1
V5
X10
L50
C100
D500
M1,000

Negative Numbers and Range

We cannot represent negative numbers using Roman Numbers. The largest number you can write in Roman numerals is 3,999 which is MMMCMXCIX Numbers larger than 3,999 in Roman numerals is represented using an overline. An overline on a Roman numeral means we are multiplying that Roman numeral by 1,000. For the number 50,000 in Roman numerals, you would use the Roman numeral L (50) with an overline to make it 50,000

Conversion Rules

I can be placed before V or X, represents subtract one, so IV (5-1) = 4 and 9 is IX (10-1)=9. 
X can be placed before L or C represents subtract ten, so XL (50-10) = 40 and XC (100-10)=90. 
C placed before D or M represents subtract hundred, so CD (500-100)=400 and CM (1000-100)=900. Roman numerals are usually written in highest to lowest from left to right except for some special cases where the left character is less than the right character.

Implementation

The algorithm is simple 
1) Place the roman literals in an array 
2) Place corresponding integer values (numbers) in another array maintaining the corresponding indices. 
3) Try subtracting the biggest number from the numbers array from the input value until the input is 0. 
4) Append the corresponding roman literal to output String.

ToRoman.java
The following class defines a method that accepts an integer and returns a Roman Number in the form of a String object.
 /**
   * I can be placed before V or X
   * 
   * X can be placed before L or C
   * 
   * C can be placed before D or M
   * 
   * 
   */
  public static String convertToRomanNumber(int num) {

    int number[] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
    String roman[] = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};

    StringBuilder result = new StringBuilder();
    for (int i = 0; i < number.length; i++) {
      while (num >= number[i]) {
          num = num - number[i];
          result = result.append(roman[i]);
      }
    }

    return result.toString();
  }
Console
System.out.println("Integer 4 : Roman " + RomanNumbers.convertToRomanNumber(4)); System.out.println("Integer 100 : Roman " + RomanNumbers.convertToRomanNumber(100)); System.out.println("Integer 2000 : Roman " + RomanNumbers.convertToRomanNumber(2000)); System.out.println("Integer 3,999 : Roman " + RomanNumbers.convertToRomanNumber(3999)); Integer 4 : Roman IV Integer 100 : Roman C Integer 2000 : Roman MM Integer 3,999 : Roman MMMCMXCIX

References

No comments :

Post a Comment

Please leave your message queries or suggetions.