https://leetcode.com/problems/integer-to-roman/description/
Integer to Roman
Roman numerals are represented by seven different symbols: I
, V
, X
, L
, C
, D
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 beforeV
(5) andX
(10) to make 4 and 9.X
can be placed beforeL
(50) andC
(100) to make 40 and 90.C
can be placed beforeD
(500) andM
(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