Sharing my really simple solution with explanation


  • 19
    Z
    string intToRoman(int num) {
        string table[4][10] = {{"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"},
                               {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"},
                               {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"},
                               {"", "M", "MM", "MMM"}
                              };
        string result;
        int count = 0;
        while(num > 0){
            int temp = num % 10;
            result = table[count][temp] + result;
            num /= 10;
            count++;
        }
        return result;
    }
    

    The basic idea is really simple: replace every digit in num by roman numerals.

    For example, we have a num: 2438.

    2 --> "MM"

    4 --> "CD"

    3 --> "XXX"

    8 --> "VIII"

    Then the result is "MMCDXXXVIII".


Log in to reply
 

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