# 12. 整数转罗马数字

字符          数值
I             1
V             5
X             10
L             50
C             100
D             500
M             1000

• I 可以放在 V (5) 和 X (10) 的左边，来表示 4 和 9。
• X 可以放在 L (50) 和 C (100) 的左边，来表示 40 和 90。
• C 可以放在 D (500) 和 M (1000) 的左边，来表示 400 和 900。

输入: 3

输入: 4

输入: 9

输入: 58



输入: 1994

• 1 <= num <= 3999

### recursive

class Solution:
def intToRoman(self, num: int) -> str:
dict = {1:'I',5:'V',10:'X',50:'L',100:'C',500:'D',1000:'M'}
special=[4,9,40,90,400,900]
special_dict={4:'IV',9:'IX',40:'XL',90:'XC',400:'CD',900:'CM'}

if num==0:
return ''
if str(num)[0]=='4':
base=400
while num-base<0:
base//=10
# Recursive
return special_dict[base]+self.intToRoman(num-base)
if str(num)[0]=='9':
base=900
while num-base<0:
base//=10
# Recursive
return special_dict[base]+self.intToRoman(num-base)

#see if num>500 or num>1000
keys = sorted(list(dict.keys()),reverse=True)
for base in keys:
if num//base>0:
i = num//base
# Recursive
return dict[base]*i+self.intToRoman(num%base)

### taxonom

class Solution:
def intToRoman(self, num: int) -> str:
roman =['M','D','C','L','X','V','I']
nums =[1000,500,100,50,10,5,1]
res =''
# divided into 1-3 4 5 6-8 9
for i in range(0,len(nums),2):
x = num//nums[i]
if x<4:
res+=(roman[i]*x)
if x==4:
res+=roman[i]+roman[i-1]
if x==5:
res+=roman[i-1]
if x>5 and x<9:
# more than 5 parts
res+=(roman[i-1]+roman[i]*(x-5))
if x==9:
res+=roman[i]+roman[i-2]
num%=nums[i]
return res

posted @ 2021-05-14 13:27  XXXSANS  阅读(70)  评论(0编辑  收藏  举报