leetcode power button 12. The Roman numerals Integer

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

Numerical character
the I. 1
V. 5
X-10
L 50
C 100
D 500
M 1000
, for example, 2 written as Roman numerals II, namely 1.12 written as two parallel XII, namely 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:

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, IV = 4.

Mainly used a python dictionary to store information

class Solution:
    def intToRoman(self, num: int) -> str:
        hashmap = {1000: 'M', 900: 'CM', 500: 'D', 400: 'CD', 
    	100: 'C', 90: 'XC', 50: 'L', 40: 'XL', 10: 'X', 
    	9: 'IX', 5: 'V', 4: 'IV', 1: 'I'}
        s = ""
        for k in hashmap:
            if (num // k) != 0:
                count = num // k
                num %= k
                s += hashmap[k] * count
        return s

 

Published 302 original articles · won praise 161 · views 490 000 +

Guess you like

Origin blog.csdn.net/qq_32146369/article/details/104104711