Integer To Roman Algorithm

The Integer to Roman Algorithm is a widely-used programming approach that converts an integer value into its corresponding Roman numeral representation. Roman numerals are a numeral system that originated in ancient Rome and were used throughout the Roman Empire. In this system, certain letters represent specific integer values, such as I (1), V (5), X (10), L (50), C (100), D (500), and M (1000). The algorithm works by comparing the input integer value with the Roman numeral values and constructing the output Roman numeral using the symbols in a systematic manner. The algorithm for converting an integer to a Roman numeral follows a set of predefined rules and mappings. It starts by creating an ordered mapping of the Roman numeral symbols to their corresponding integer values. The algorithm iterates through the mapping, starting with the highest integer value, and checks if the current integer value can be subtracted from the input integer. If it can, the corresponding Roman numeral symbol is added to the output string, and the input integer is reduced by the current integer value. This process continues until the input integer is reduced to zero. The final output string will be the Roman numeral representation of the input integer. The algorithm's simplicity and efficiency make it a popular choice for developers and programmers working on applications that involve Roman numerals.
package Conversions;

/**
 * Converting Integers into Roman Numerals
 *
 *('I', 1);
 *('IV',4);
 *('V', 5);
 *('IV',9);
 *('X', 10);
 *('XL',40;
 *('L', 50);
 *('XC',90);
 *('C', 100);
 *('D', 500);
 *('M', 1000);
 *
 */


public class IntegerToRoman {
    private static int[] allArabianRomanNumbers = new int[]{1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
    private static String[] allRomanNumbers = new String[]{"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};

    //Value must be > 0

    public static String integerToRoman(int num) {
        if (num <= 0) {
            return "";
        }

        StringBuilder builder = new StringBuilder();

        for (int a = 0; a < allArabianRomanNumbers.length; a++) {
            int times = num / allArabianRomanNumbers[a];
            for (int b = 0; b < times; b++) {
                builder.append(allRomanNumbers[a]);
            }

            num -= times * allArabianRomanNumbers[a];
        }

        return builder.toString();
    }

    public static void main(String[] args) {
        System.out.println(IntegerToRoman.integerToRoman(2131));
    }
}

LANGUAGE:

DARK MODE: