12. 整数转罗马数字

该文章讨论了一种将整数转换为罗马数字的方法,首先通过从高位到低位遍历来实现,然后通过引入哈希表来优化代码,减少冗余逻辑,提高效率。
摘要由CSDN通过智能技术生成

题目描述

 方法:

1. 从高位开始遍历减去

class Solution:
    def intToRoman(self, num: int) -> str:
        res = []
        while num > 0:
            if num >= 1000:
                res.append("M")
                num -= 1000
            elif num >= 500:
                if num >= 900:
                    res.append("CM")
                    num -= 900
                else:
                    res.append("D")
                    num -= 500
            elif num >= 100:
                if num >= 400:
                    res.append("CD")
                    num -= 400
                else:
                    res.append("C")
                    num -= 100
            elif num >= 50:
                if num >= 90:
                    res.append("XC")
                    num -= 90
                else:
                    res.append("L")
                    num -= 50
            elif num >= 10:
                if num >= 40:
                    res.append("XL")
                    num -= 40
                else:
                    res.append("X")
                    num -= 10
            elif num >= 5:
                if num >= 9:
                    res.append("IX")
                    num -= 9
                else:
                    res.append("V")
                    num -= 5
            elif num >= 1:
                if num >= 4:
                    res.append("IV")
                    num -= 4
                else:
                    res.append("I")
                    num -= 1

        return "".join(res)

缺点: 代码太冗长

2. 利用哈希表优化代码,逻辑不变

class Solution:
    def intToRoman(self, num: int) -> str:
        res = []
        roma = {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"}

        for key in roma:
            while num>=key:
                num -= key
                res.append(roma[key])
        return "".join(res)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值