【Leetcode-算法-Python3】12. 整数转罗马数字/Integer to Roman

IDEAs

- Find the biggest symbol and add the symbol(s) into the result (process 6 special instances).

- Subtract the value of above symbol(s).

- Stop until the difference equals 0.

 

Submission Detail

3999 / 3999 test cases passed.

Status: 

Accepted

Runtime: 200 ms

Memory Usage: 12.7 MB

 

CODE

class Solution:
    def intToRoman(self, num: 'int') -> 'str':
        sym = [1, 5, 10, 50, 100, 500, 1000]
        temp = num
        re = ""
        while temp > 0 :
            loc = -1
            for i in range(len(sym) - 1):
                if temp >= sym[i] and temp <sym[i+1]:
                    loc = i
                    break
            # 1~4 (I, IV)
            if loc == 0 and temp >= 4:
                re = re + "IV"
                temp = temp - 4
            elif loc == 0 and temp != 4:
                re = re + "I"*temp
                temp = temp - temp
            # 5~9 (V, IX)
            elif loc == 1 and temp >= 9:
                re = re + "IX"
                temp = temp - 9
            elif loc == 1 and temp != 9:
                re = re + "V"
                temp = temp - 5
            # 10~49 (X, XL)
            elif loc == 2 and temp >=40:
                re = re + "XL"
                temp = temp -40
            elif loc == 2 and temp != 40:
                re = re + "X"*(temp // 10)
                temp = temp - 10 * (temp // 10)
            # 50~99 (L, XC)
            elif loc == 3 and temp >= 90:
                re = re + "XC"
                temp = temp - 90
            elif loc == 3 and temp != 90:
                re = re + "L"
                temp = temp - 50
            # 100~499 (C, CD)
            elif loc == 4 and temp >= 400:
                re = re + "CD"
                temp = temp - 400
            elif loc == 4 and temp != 400:
                re = re + "C" * (temp//100)
                temp = temp - 100 * (temp//100)
            # 500~999 (D, CM)
            elif loc == 5 and temp >= 900:
                re = re + "CM"
                temp = temp - 900
            elif loc == 5 and temp != 900:
                re = re + "D"
                temp = temp - 500
            # >=1000 (M)
            elif loc == -1:
                re = re + "M" * (temp // 1000)
                temp = temp - 1000 * (temp // 1000)
        return re

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值