Wednesday, 13 July 2016

How to convert a number into roman numerals ?


Roman numerals uses digits :
I = 1
V = 5
X = 10
L = 50
C = 100
D = 500
M = 1000

Note : No need to be able to convert numbers larger than about 3000
(The Romans themselves didn't tend to go any higher) 

Example : 1990
1000=M, 900=CM, 90=XC
MCMXC

Example : 2008 
2000=MM, 8=VIII
MMVIII


Solution
public static String convertToRoman(int num) {
    // Extract the digit at particular position from 4 to 1
    int units = num % 10;
    int tens = (num % 100)/10;
    int hundred = (num % 1000)/100;
    int thousand = (num % 10000)/1000;
  
    System.out.println("units " + units);
    System.out.println("tens " + tens);
    System.out.println("hundred " + hundred);
    System.out.println("thousand " + thousand);


    // Evaluate individually each digit and concatenate the result
    return eval(thousand, "M", " ", " ")
            + eval(hundred, "C", "D", "M")
              + eval(tens, "X", "L", "C")
                + eval(units, "I", "V", "X");
}
 

private static String eval(int n, String one, String five, String ten) {
    // Skip for digit = 0
    if (n == 0) {
        return "";
    }


    /* Evaluate the roman representation */

    StringBuilder roman = new StringBuilder(1024);

    // Add FIVE for 4 to 8

    if (n >= 4 && n <= 8) {
        roman.append(five);
    }


    // Add TEN for 9

    if (n==9) {
        roman.append(ten);
    }


    // Add multiple ONEs for n%5<4 (1, 2, 3 and 6, 7, 8)

    if (n%5 < 4) {
        while (n%5 > 0) {
            roman.append(one);
            n--;
        }
    }


    // Add ONE before current expression for n%5==4 (4 and 8)

    if (n%5 == 4) {
        String romanStr = one + roman.toString();
        roman = new StringBuilder(romanStr);
    }

  
    return roman.toString();
}

No comments:

Post a Comment

Note: only a member of this blog may post a comment.