Java arithmetic exercises - Integer to Roman numerals

Topic Link

Title Description

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

character Numerical
I 1
V 5
X 10
L 50
C 100
D 500
M 1000

For example, written as a Roman numeral 2 II, shall be written as two parallel 1.12 XII, that is X + II. 27 written as XXVII, namely XX + V + II.

Typically, small numbers of Roman numerals to the right in large numbers. But there are exceptions, for example, do not write 4 IIII, but IV. In the left number 5 number 1, the number of large numbers equal to the value represented by a reduced number 5 obtained 4. Likewise, the number 9 is represented as IX. This special rule applies only to the following six cases:

  • I may be on the left V (5) and X (10), and to represent 4 and 9.
  • X L can be placed on the left (50) and C (100), and 40 and 90 are represented.
  • C may be placed on D (500) and M (1000) to the left, to 400 and 900 represent.

Given an integer, convert it to a Roman numeral. To ensure that the input is in the range of 1 to 3999.

Example 1

输入: 3
输出: "III"

Example 2

输入: 4
输出: "IV"

Example 3

输入: 9
输出: "IX"

Example 4

输入: 58
输出: "LVIII"
解释: L = 50, V = 5, III = 3.

Example 5

输入: 1994
输出: "MCMXCIV"
解释: M = 1000, CM = 900, XC = 90, IV = 4.

answer

public String intToRoman(int num) {
        Map<Integer, String> lookup = new LinkedHashMap<>();
        lookup.put(1000, "M");
        lookup.put(900, "CM");
        lookup.put(500, "D");
        lookup.put(400, "CD");
        lookup.put(100, "C");
        lookup.put(90, "XC");
        lookup.put(50, "L");
        lookup.put(40, "XL");
        lookup.put(10, "X");
        lookup.put(9, "IX");
        lookup.put(5, "V");
        lookup.put(4, "IV");
        lookup.put(1, "I");

        StringBuilder res = new StringBuilder();

        for (Integer key : lookup.keySet()) {
            int n = num / key;
            if (n == 0) continue;
            for (int i = n; i > 0; i--) {
                res.append(lookup.get(key));
            }
            num -= n * key;
            if (num == 0) {
                break;
            }
        }
        return res.toString();
    }

Complexity Analysis

  • Time complexity: $ O (n) $, although two cycles, but the second up to 3 cycles.
  • Space complexity: $ O (n) $.

Notes

LinkedHashMap can store the key-value pair insertion order.

Guess you like

Origin www.cnblogs.com/mxwbq/p/10956786.html