Convert integer to a Roman numeral. - Java java.lang

Java examples for java.lang:Number

Description

Convert integer to a Roman numeral.

Demo Code

/*   Please see the license information at the end of this file. */
//package com.java2s;

public class Main {
    /**   Roman numeral strings. */

    protected static String[] romanNumerals = new String[] { "M", "CM",
            "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" };
    /**   Integer values for entries in "romanNumerals". */

    protected static int[] integerValues = new int[] { 1000, 900, 500, 400,
            100, 90, 50, 40, 10, 9, 5, 4, 1 };

    /**   Convert integer to a Roman numeral.
     */*ww  w  .  j  av a  2s  .  c  om*/
     *   @param   n   The integer to convert to a Roman numeral.
     *
     *   @return      The corresponding Roman numeral as a string.
     */

    protected static String integerToRoman(int n) {
        StringBuffer result = new StringBuffer();

        int i = 0;
        //   Compute Roman numeral string using
        //   successive substraction of
        //   breakpoint values for Roman numerals.
        while (n > 0) {
            while (n >= integerValues[i]) {
                result.append(romanNumerals[i]);
                n -= integerValues[i];
            }

            i++;
        }

        return result.toString();
    }
}

Related Tutorials