|
| 1 | +### [12\. Integer to Roman](https://leetcode.com/problems/integer-to-roman/) |
| 2 | + |
| 3 | +Difficulty: **Medium** |
| 4 | + |
| 5 | + |
| 6 | +Roman numerals are represented by seven different symbols: `I`, `V`, `X`, `L`, `C`, `D` and `M`. |
| 7 | + |
| 8 | +``` |
| 9 | +Symbol Value |
| 10 | +I 1 |
| 11 | +V 5 |
| 12 | +X 10 |
| 13 | +L 50 |
| 14 | +C 100 |
| 15 | +D 500 |
| 16 | +M 1000``` |
| 17 | +
|
| 18 | +For example, two is written as `II` in Roman numeral, just two one's added together. Twelve is written as, `XII`, which is simply `X` + `II`. The number twenty seven is written as `XXVII`, which is `XX` + `V` + `II`. |
| 19 | +
|
| 20 | +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: |
| 21 | +
|
| 22 | +* `I` can be placed before `V` (5) and `X` (10) to make 4 and 9. |
| 23 | +* `X` can be placed before `L` (50) and `C` (100) to make 40 and 90. |
| 24 | +* `C` can be placed before `D` (500) and `M` (1000) to make 400 and 900. |
| 25 | +
|
| 26 | +Given an integer, convert it to a roman numeral. Input is guaranteed to be within the range from 1 to 3999. |
| 27 | +
|
| 28 | +**Example 1:** |
| 29 | +
|
| 30 | +``` |
| 31 | +Input: 3 |
| 32 | +Output: "III"``` |
| 33 | + |
| 34 | +**Example 2:** |
| 35 | + |
| 36 | +``` |
| 37 | +Input: 4 |
| 38 | +Output: "IV"``` |
| 39 | +
|
| 40 | +**Example 3:** |
| 41 | +
|
| 42 | +``` |
| 43 | +Input: 9 |
| 44 | +Output: "IX"``` |
| 45 | + |
| 46 | +**Example 4:** |
| 47 | + |
| 48 | +``` |
| 49 | +Input: 58 |
| 50 | +Output: "LVIII" |
| 51 | +Explanation: L = 50, V = 5, III = 3. |
| 52 | +``` |
| 53 | + |
| 54 | +**Example 5:** |
| 55 | + |
| 56 | +``` |
| 57 | +Input: 1994 |
| 58 | +Output: "MCMXCIV" |
| 59 | +Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.``` |
| 60 | +
|
| 61 | +
|
| 62 | +#### Solution |
| 63 | +
|
| 64 | +Language: **Java** |
| 65 | +
|
| 66 | +```java |
| 67 | +class Solution { |
| 68 | + public String intToRoman(int num) { |
| 69 | + String M[] = {"", "M", "MM", "MMM"}; |
| 70 | + String C[] = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"}; |
| 71 | + String X[] = {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"}; |
| 72 | + String I[] = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"}; |
| 73 | + return M[num/1000] + C[(num%1000)/100] + X[(num%100)/10] + I[num%10]; |
| 74 | + } |
| 75 | +} |
| 76 | +``` |
0 commit comments