列表

详情


12. 整数转罗马数字

罗马数字包含以下七种字符: I, V, X, LCD 和 M

字符          数值
I             1
V             5
X             10
L             50
C             100
D             500
M             1000

例如, 罗马数字 2 写做 II ,即为两个并列的 1。12 写做 XII ,即为 X + II 。 27 写做  XXVII, 即为 XX + V + II 。

通常情况下,罗马数字中小的数字在大的数字的右边。但也存在特例,例如 4 不写做 IIII,而是 IV。数字 1 在数字 5 的左边,所表示的数等于大数 5 减小数 1 得到的数值 4 。同样地,数字 9 表示为 IX。这个特殊的规则只适用于以下六种情况:

给你一个整数,将其转为罗马数字。

 

示例 1:

输入: num = 3
输出: "III"

示例 2:

输入: num = 4
输出: "IV"

示例 3:

输入: num = 9
输出: "IX"

示例 4:

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

示例 5:

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

 

提示:

相似题目

罗马数字转整数

整数转换英文表示

原站题解

去查看

上次编辑到这里,代码来自缓存 点击恢复默认模板
class Solution { public: string intToRoman(int num) { } };

golang 解法, 执行用时: 8 ms, 内存消耗: 3.4 MB, 提交时间: 2021-05-14 18:37:38

func intToRoman(num int) string {
    values := []int{1000,900,500,400,100,90,50,40,10,9,5,4,1}
    resp := []string{"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"}
    ans := ""
    for i:=0; i<len(values); i++ {
        for num >= values[i] {
            num -= values[i]
            ans += resp[i]
        }
    }
    return ans
}

golang 解法, 执行用时: 16 ms, 内存消耗: 3.6 MB, 提交时间: 2020-12-02 15:56:37

func intToRoman(num int) string {
    values := []int{1000,900,500,400,100,90,50,40,10,9,5,4,1}
    resp := []string{"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"}
    ans := ""
    for i:=0; i<len(values); i++ {
        for num >= values[i] {
            num -= values[i]
            ans += resp[i]
        }
    }
    return ans

}

python3 解法, 执行用时: 60 ms, 内存消耗: 13.6 MB, 提交时间: 2020-12-02 15:53:42

class Solution:
    def intToRoman(self, num: int) -> str:
        values = [1000,900,500,400,100,90,50,40,10,9,5,4,1]
        resp = ["M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"]
        ans = ''
        for i in range(13):
            while num >= values[i]:
                num -= values[i]
                ans += resp[i]
        return ans

python3 解法, 执行用时: 148 ms, 内存消耗: N/A, 提交时间: 2018-08-24 14:00:37

class Solution:
    def intToRoman(self, num):
        """
        :type num: int
        :rtype: str
        """
        k = str(num)
        l = len(k)
        r = ''
        ff = {1:'I',5:'V',10:'X',50:'L',100:'C',500:'D',1000:'M'}
        for i in range(0, l):
            a = int(k[i])
            j = 10**(l-i-1)
            if a == 9:
                r += ff[j] + ff[j*10]
            elif a > 4:
                r += ff[5*j] + (a - 5) * ff[j]
            elif a == 4:
                r += ff[j] + ff[5*j]
            else:
                r += a * ff[j]
        return r
            

上一题