12. 整数转罗马数字 @Python @Go

原题

https://leetcode.cn/problems/integer-to-roman/description/

思路

字典 + 循环

复杂度

时间:O(n)
空间:O(n)

Python代码

class Solution:
    def intToRoman(self, num: int) -> str:
        def process(i, base):
            nonlocal ans
            d = dict(zip([1, 5, 10, 50, 100, 500, 1000], 'IVXLCDM'))
            if 1 <= i <= 3:
                ans += d[base] * i 
            elif i == 4:
                ans += d[base] + d[base * 5]
            elif 5 <= i <= 8:
                ans += d[base * 5] + d[base] * (i -5)
            elif i == 9:
                ans += d[base] + d[base * 10]                

        ans = ''
        while num > 0:
            if num >= 1000:
                i, num = divmod(num, 1000)
                process(i, 1000)
            elif num >= 100:
                i, num = divmod(num, 100)
                process(i, 100)
            elif num >= 10:
                i, num = divmod(num, 10)
                process(i, 10)
            elif num >= 1:
                i, num = divmod(num, 1)
                process(i, 1)
        return ans
        

Go代码

func process(i int, base int) string {
	// 创建 Map
	m := map[int]string{
		1:    "I",
		5:    "V",
		10:   "X",
		50:   "L",
		100:  "C",
		500:  "D",
		1000: "M",
	}
	if 1 <= i && i <= 3 {
		return strings.Repeat(m[base], i)
	} else if i == 4 {
		return m[base] + m[base*5]
	} else if 5 <= i && i <= 8 {
		return m[base*5] + strings.Repeat(m[base], i-5)
	} else {
		return m[base] + m[base*10]
	}
}

func intToRoman(num int) string {
	var ans string
	var i int
	for num > 0 {
		if num >= 1000 {
			i = num / 1000
			num %= 1000
			ans += process(i, 1000)
		} else if num >= 100 {
			i = num / 100
			num %= 100
			ans += process(i, 100)
		} else if num >= 10 {
			i = num / 10
			num %= 10
			ans += process(i, 10)
		} else if num >= 1 {
			i = num / 1
			num %= 1
			ans += process(i, 1)
		}
	}
	return ans
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值