Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
意思就是用罗马数字表示一个整数,此外另外还有几个规则:
- 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.
思路
很简单,一次除以1000,500,…,5,1。但是因为4可以用IV表示,9可以用IX表示,40可以用XL表示,就是可以呀XC表示,400可以用CD表示,900可以用CM表示。所以还要考虑几个特殊的情况。详情见下面的注释。
class Solution:
def intToRoman(self, num: int) -> str:
ans = ""
RN = {"1":"I",
"4":"IV",
"5":"V",
"9":"IX",
"10":"X",
"40":"XL",
"50":"L",
"90":"XC",
"100":"C",
"400":"CD",
"500":"D",
"900":"CM",
"1000":"M"}
a = (int)(num/1000)
b = num%1000
ans+=RN[str(1000)]*a
if b >=900:
b = b - 900
ans+=RN[str(900)]
else:
if b >= 400 and b < 500:
b = b - 400
ans+=RN[str(400)]
# 最终保证余数b在[0,100)和(100,400)以及(400,900)之间。
# 从而使得400,900可以直接表示出来。
if b == 0:
return ans
print("b : ",b)
c = (int)(b/500) # 不可能有两个500,只有1个或0个,所以直接考虑余数,下面的50和5同理
d = b%500
ans+=RN[str(500)]*c
if d == 0:
return ans
print("d : ",d)
e = (int)(d/100)
f = d%100
ans+=RN[str(100)]*e
if f >= 90:
f = f - 90
ans+=RN[str(90)]
else:
if f >= 40 and f < 50:
f = f - 40
ans+=RN[str(40)]
if f == 0:
return ans
print("f : ",f)
g = (int)(f/50)
h = f%50
ans+=RN[str(50)]*g
if h == 0:
return ans
print("h : ", g, h)
i = (int)(h/10)
j = h%10
ans+=RN[str(10)]*i
if j >= 9:
j = j - 9
ans+=RN[str(9)]
else:
if j >= 4 and j < 5:
j = j - 4
ans+=RN[str(4)]
if j == 0:
return ans
print("j : ",j)
k = (int)(j/5)
l = j%5
ans+=RN[str(5)]*k+RN[str(1)]*l
return ans
THE END.