Skip to content
Rain Hu's Workspace
Go back

[Leetcode] 12. Integer to Roman

Rain Hu

12. Integer to Roman


一、題目

Roman numerals are represented by seven different symbols: I, V, X, L, C, D, and M.
\(\boxed{\begin{array}{ll} \textbf{Symbol}&\textbf{Value}\\ \texttt{I}&1\\ \texttt{V}&5\\ \texttt{X}&10\\ \texttt{L}&50\\ \texttt{C}&100\\ \texttt{D}&500\\ \texttt{M}&1000\\ \end{array}}\)
For example, 2 is written as II in Roman numeral, just two one’s added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II.
Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:

Example 1:

Example 2:

Example 3:

Constraints:


二、分析

三、解題

1. Math

string intToRoman(int num) {
    string M[] = {"", "M", "MM", "MMM"};
    string C[] = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"};
    string X[] = {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"};
    string I[] = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"};
    return M[num/1000] + C[(num%1000)/100] + X[(num%100)/10] + I[num%10];
}

回目錄 Catalog


Share this post on:

Previous
[LeetCode] 2653. Sliding Subarray Beauty
Next
[Leetcode] 11. Container With Most Water