Leetcode 12 13: Integer to Roman, Roman to Integer

本文详细解析了如何将整数转换为罗马数字,并反向转换的算法实现。通过两个Python类方法,分别实现了整数到罗马数字及罗马数字到整数的转换,覆盖了从1到3999的范围。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

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

Integer to Roman

Roman numerals are represented by seven different symbols: IVXLCD and M.

Symbol       Value
I             1
V             5
X             10
L             50
C             100
D             500
M             1000

For example, two is written as II in Roman numeral, just two one's added together. Twelve is written as, XII, which is simply X + II. The number twenty seven is written as XXVII, which is XX + V + II.

Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:

  • I can be placed before V (5) and X (10) to make 4 and 9. 
  • X can be placed before L (50) and C (100) to make 40 and 90. 
  • C can be placed before D (500) and M (1000) to make 400 and 900.

Given an integer, convert it to a roman numeral. Input is guaranteed to be within the range from 1 to 3999.

这道题特殊在它限定了范围,所以可以将所有情况都列出来,其实所有的情况并不多,只有以下几种:

class Solution(object):
    def intToRoman(self, num):

        #greedy function
        ans=[]
        nums=[1000,900,500,400,100,90,50,40,10,9,5,4,1]
        roman=['M','CM','D','CD','C','XC','L','XL','X','IX','V','IV','I']
        for i in range(len(nums)):
            while num>=nums[i]:
                num=num-nums[i]
                ans.append(roman[i])
        return ''.join(ans)

上面的解法比较简单,还有一种通用的解法。在4和9的时候有特殊情况,所以分成四段处理。

class Solution(object):
    def intToRoman(self, num):
        
        ans=''
        nums=[1000,500,100,50,10,5,1]
        roman=['M','D','C','L','X','V','I']
        i=0
        while i<7:
            tmp=num/nums[i]
            if tmp<4:
                for j in range(1,tmp+1):
                    ans+=roman[i]
            elif tmp==4:
                ans=ans+roman[i]+roman[i-1]
            elif tmp>4 and tmp<9:
                ans+=roman[i-1]
                for j in range(6,tmp+1):
                    ans+=roman[i]
            elif tmp==9:
                ans=ans+roman[i]+roman[i-2]
            num=num%nums[i]
            i+=2
        return ans
                

这里需要注意的是,首先做了一步tmp=num/nums[i],想一下如果是3千多的话,首先肯定是MMM,所以<4的时候重复,==4的时候我们看4表示为IV;40表示为XL。这里roman[i]和roman[i-1]一定是1和5这种数,不会有别的情况,所以可以如代码中的写法。最后%操作的效果是将当前位后移。

Roman to Integer

与上题类似,这里可以还用上一道题的方法,罗马转数字比较容易,特殊的情况只有4和9,这时一个数字用两个罗马符号表示

class Solution(object):
    def romanToInt(self, s):
        """
        :type s: str
        :rtype: int
        """
        nums=[1000,900,500,400,100,90,50,40,10,9,5,4,1]
        roman=['M','CM','D','CD','C','XC','L','XL','X','IX','V','IV','I']
        i=0
        result=0
        while i<len(s):
            if s[i:i+2] in roman:
                result+= nums[roman.index(s[i:i+2])]
                i+=2
            else:
                result+=nums[roman.index(s[i])]
                i+=1     
        return result

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值