package com.thealgorithms.conversions; /** * A utility class to convert integers into Roman numerals. * *

Roman numerals follow these rules: *

* *

Conversion is based on repeatedly subtracting the largest possible Roman numeral value * from the input number until it reaches zero. For example, 1994 is converted as: *

 *   1994 -> MCMXCIV (1000 + 900 + 90 + 4)
 * 
*/ public final class IntegerToRoman { // Array of Roman numeral values in descending order private static final int[] ALL_ROMAN_NUMBERS_IN_ARABIC = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; // Corresponding Roman numeral symbols private static final String[] ALL_ROMAN_NUMBERS = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}; private IntegerToRoman() { } /** * Converts an integer to its Roman numeral representation. * Steps: *
    *
  1. Iterate over the Roman numeral values in descending order
  2. *
  3. Calculate how many times a numeral fits
  4. *
  5. Append the corresponding symbol
  6. *
  7. Subtract the value from the number
  8. *
  9. Repeat until the number is zero
  10. *
  11. Return the Roman numeral representation
  12. *
* * @param num the integer value to convert (must be greater than 0) * @return the Roman numeral representation of the input integer * or an empty string if the input is non-positive */ public static String integerToRoman(int num) { if (num <= 0) { return ""; } StringBuilder builder = new StringBuilder(); for (int i = 0; i < ALL_ROMAN_NUMBERS_IN_ARABIC.length; i++) { int times = num / ALL_ROMAN_NUMBERS_IN_ARABIC[i]; builder.append(ALL_ROMAN_NUMBERS[i].repeat(Math.max(0, times))); num -= times * ALL_ROMAN_NUMBERS_IN_ARABIC[i]; } return builder.toString(); } }