Ac solution code


  • 0

    The basic idea is using a table(10x4) to present Roman strings corresponding to 10-scale value:

    1..9
    10..90
    100..900
    1000..3000
    
    {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"},// 1..9
    {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"},// 10..90
    {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"},// 100..900
    {"", "M", "MM", "MMM"}									     // 1000..3000   
    

    And then divide 10 each step, check Roman string in the table corresponding to the remainder, pre-append it to the result. Keep the above steps recursively.

    JAVA Code:

     public String intToRoman(int num) {
        // Row = 4, Column = 10
        String table[][] =    {{"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"},// 1..9
                               {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"},// 10..90
                               {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"},// 100..900
                               {"", "M", "MM", "MMM"}                                       // 1000..3000
                              };
        String res = ""; 
        int digit = 0;
        while(num > 0) {// Start from lowest value to highest: right-most=>left-most; 1=>1000
            int value = num % 10;// Current 10-scale value
            res = table[digit][value] + res;// Pre-append Roman string
            num /= 10;
            digit++;
        }
        return res;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.