12/13 Convert between Integer and Roman

Given an integer, convert it to a roman numeral.

Input is guaranteed to be within the range from 1 to 3999.

public class Solution {
    public String intToRoman(int num) {
            }
}

To solve this problem, there's some basic knowledge we need to be familiar with:

  1. How Roman represents the digits:
Roman Digit
I 1
IV 4
V 5
IX 9
X 10
XL 40
L 50
XC 90
C 100
CD 400
D 500
CM 900
M 1000
  • The roman character cannot repeat more than 3 times.

  • After understand the regular pattern of Roman, we can use these 13 base to convert the integer to Roman.

  • Be careful about the order of the elements in two sets. The comparison should start with the largest base


Code: public static String intToRoman(int num) { String[] sign = {"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I" }; int[] digit = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; StringBuffer result = new StringBuffer(); for (int i=0; i<13; i++)="" {="" the="" comparison="" starts="" from="" largest="" base="" if(num="">=digit[i]) { int count = num/digit[i]; //The remainder becomes the new number num %= digit[i]; for(int j=0; j<count; j++) { //Append "count" numbers of base sign result.append(sign[i]); } } } return result.toString(); }

public static int toInt(char rom)
{
    switch(rom)
    {
        case 'I' : return 1;
        case 'V' : return 5;
        case 'X' : return 10;
        case 'L' : return 50;
        case 'C' : return 100;
        case 'D' : return 500;
        case 'M' : return 1000;
        default: return 0;
    }

}


public static int RomanToInt(String rom)
{
    //Or have the toInt inside this function
    int total=0;
    int sign = 0;
    //or string.chatAt(i);
    char[] single = rom.toCharArray();

    for(int i=0; i<rom.length()-1; i++)
    {
        if(toInt(rom.charAt(i))<toInt(rom.charAt(i+1)))
        {
            total -= toInt(rom.charAt(i)) ;
        }
        else
        {
            total +=toInt(rom.charAt(i));
        }
    }

    return total+toInt(rom.charAt(rom.length()-1));
}


public static void main(String[] args)
{
    //IntToRoman Test
    int[] num = {2795, 1250, 700, 86, 5, 1};
    for(int i=0; i<num.length; i++)
    {
        System.out.println(num[i] + " convert to Roman:" + intToRoman(num[i]));
    }

    //RomanToInt Test
    String[] roman = {"MMDCCXCV", "MCCL", "DCC", "LXXXVI", "V", "I"};
    for(int i=0; i<roman.length; i++)
    {
        System.out.println(roman[i] + " convert to Int:" + RomanToInt(roman[i]));
    }
}

results matching ""

    No results matching ""