Leetcode: 12. Integer to Roman

Description

Given an integer, convert it to a roman numeral.

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

思路

  • 这个也没啥好说的吧,首先搞清楚罗马数字是个什么鬼?
  • 基本字符:I(1), V(5), X(10), L(50), C(100), D(500), M(1000)
  • 相同的数字连写、所表示的数等于这些数字相加得到的数、如:Ⅲ=3
  • 小的数字在大的数字的右边、所表示的数等于这些数字相加得到的数、如:Ⅷ=8、Ⅻ=12
  • 小的数字(限于 I、X 和C)在大的数字的左边、所表示的数等于大数减小数得到的数、如:Ⅳ=4、Ⅸ=9
  • 正常使用时、连写的数字重复不得超过三次
  • 在一个数的上面画一条横线、表示这个数扩大 1000 倍。

代码

class Solution {
public:
    string intToRoman(int num) {
        string str[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 res;
        res += str[3][((num / 1000) % 10)];
        res += str[2][((num / 100) % 10)];
        res += str[1][((num / 10) % 10)];
        res += str[0][num % 10];
        
        return res;
    }
};