These days work very tired, fortunately the result is good nevertheless, the weekend sees the words that have time to be able to write a few comprehension recently. Continue to do one leetcode, I hope one leetcode every day, no more, what matters is persistence.

The title

Roman numerals contain the following seven characters: I, V, X, L, C, D and M.

Character value I 1 V 5 X 10 L 50 C 100 D 500 M 1000 For example, the Roman numeral 2 is written as II, which is the parallel 1. Write XII as X + II. Write XXVII as XX + V + II.

Usually, the smaller Roman numerals are to the right of the larger numerals. But there are exceptions, for example, 4 is not written as IIII, it’s written as IV. The number 1 is to the left of the number 5 and represents the number 4 when the larger number 5 decreases by 1. Similarly, the number 9 represents IX. This particular rule applies only to the following six situations:

I can be put to the left of V (5) and X (10) to represent 4 and 9. X can be placed to the left of L (50) and C (100) to represent 40 and 90. C can be put to the left of D (500) and M (1000) to represent 400 and 900. Give you an integer and convert it to Roman numerals.

Example 1: Input: num = 3 Output: “III”

Example 2: Input: num = 4 Output: “IV”

Example 3: Input: num = 9 Output: “IX”

Example 4: Input: num = 58 Output: “LVIII” Description: L = 50, V = 5, III = 3.

Example 5: Input: num = 1994 Output: “MCMXCIV” Description: M = 1000, CM = 900, XC = 90, IV = 4.

Train of thought

Although the difficulty is medium, in fact, it is completely water problem. Essentially, it defines a new base system that lets you convert a value in base 10 to a value in base N. Except, this is not a fixed base N, it’s a list. Let’s just give it to the code, maybe some of it could be a little more elegant, but that’s the whole idea.

Java version code

class Solution { public String intToRoman(int num) { List<Integer> list = new ArrayList<>(); list.add(1000); list.add(900); list.add(500); list.add(400); list.add(100); list.add(90); list.add(50); list.add(40); list.add(10); list.add(9); list.add(5); list.add(4); list.add(1); Map<Integer, String> map = new HashMap<>(); map.put(1000, "M"); map.put(900, "CM"); map.put(500, "D"); map.put(400, "CD"); map.put(100, "C"); map.put(90, "XC"); map.put(50, "L"); map.put(40, "XL"); map.put(10, "X"); map.put(9, "IX"); map.put(5, "V"); map.put(4, "IV"); map.put(1, "I"); StringBuilder ans = new StringBuilder(); for (Integer item : list) { if (num == 0) { break; } int count = num / item; if (count > 0) { while (count-- > 0) { ans.append(map.get(item)); } } num %= item; } return ans.toString(); }}Copy the code