友情支持

如果您觉得这个笔记对您有所帮助,看在D瓜哥码这么多字的辛苦上,请友情支持一下,D瓜哥感激不尽,😜

支付宝

微信

有些打赏的朋友希望可以加个好友,欢迎关注D 瓜哥的微信公众号,这样就可以通过公众号的回复直接给我发信息。

wx jikerizhi

公众号的微信号是: jikerizhi因为众所周知的原因,有时图片加载不出来。 如果图片加载不出来可以直接通过搜索微信号来查找我的公众号。

12. Integer to Roman

Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.

Symbol       Value
I             1
V             5
X             10
L             50
C             100
D             500
M             1000

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.

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:

  • I can be placed before V (5) and X (10) to make 4 and 9.

  • X can be placed before L (50) and C (100) to make 40 and 90.

  • C can be placed before D (500) and M (1000) to make 400 and 900.

Given an integer, convert it to a roman numeral. Input is guaranteed to be within the range from 1 to 3999.

Example 1:

Input: 3
Output: "III"

Example 2:

Input: 4
Output: "IV"

Example 3:

Input: 9
Output: "IX"

Example 4:

Input: 58
Output: "LVIII"
Explanation: L = 50, V = 5, III = 3.

Example 5:

Input: 1994
Output: "MCMXCIV"
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/**
 * Runtime: 46 ms, faster than 5.34% of Java online submissions for Integer to Roman.
 *
 * Memory Usage: 44.1 MB, less than 5.01% of Java online submissions for Integer to Roman.
 *
 * @author D瓜哥 · https://www.diguage.com
 * @since 2019-07-17 11:24:02
 */
public String intToRoman(int num) {
    Map<Integer, String> i2r = new HashMap<>(19);
    i2r.put(1, "I");
    i2r.put(5, "V");
    i2r.put(10, "X");
    i2r.put(50, "L");
    i2r.put(100, "C");
    i2r.put(500, "D");
    i2r.put(1000, "M");
    i2r.put(4, "IV");
    i2r.put(9, "IX");
    i2r.put(40, "XL");
    i2r.put(90, "XC");
    i2r.put(400, "CD");
    i2r.put(900, "CM");

    StringBuilder builder = new StringBuilder(20);

    int size = i2r.size();
    int temp = num;

    Integer[] keys = i2r.keySet().toArray(new Integer[0]);
    Arrays.sort(keys, Comparator.comparingInt(a -> -a));

    int lastIndex = 0;
    while (temp > 0) {
        for (int i = lastIndex; i < size; i++) {
            Integer key = keys[i];
            if (temp >= key) {
                lastIndex = i;
                temp -= key;
                builder.append(i2r.get(key));
                break;
            }
        }
    }

    return builder.toString();
}