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