[LeetCode][python3]0012. Integer to Roman

Start the Journey
N2I -2020.03.17

1. A clean solution


  1. class Solution:
  2. def intToRoman(self, num: int) -> str:
  3. rom = ["M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"]
  4. digit = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
  5. result = ""
  6. for d, r in zip(digit, rom):
  7. result += r * (num // d)
  8. num %= d
  9. return result
  10.  

Note:

  • zip(a,b) The function zip will zip two array items into a two tuple array. the zip array will stop when it reaches min(len(a),len(b))

  1. print("example of zip(a,b)")
  2. a=[1,2,3,4,5]
  3. b='abcdef'
  4. for n in zip(a,b):
  5. print(n)
  6. >>>(1, 'a')
  7. >>>(2, 'b')
  8. >>>(3, 'c')
  9. >>>(4, 'd')
  10. >>>(5, 'e')


2. My first try


  1. class Solution:
  2. def intToRoman(self, num: int) -> str:
  3. M=num//1000
  4. num=num%1000
  5. D=num//500
  6. num=num%500
  7. C=num//100
  8. num=num%100
  9. L=num//50
  10. num=num%50
  11. X=num//10
  12. num=num%10
  13. V=num//5
  14. I=num%5
  15. s=""
  16. if I==4:
  17. if V==0:
  18. s="IV"
  19. else:
  20. s="IX"
  21. V-=1
  22. else:
  23. s="I"*I
  24. s="V"*V+s
  25. if X==4:
  26. if L==0:
  27. s="XL"+s
  28. else:
  29. s="XC"+s
  30. L-=1
  31. else:
  32. s="X"*X+s
  33. s="L"*L+s
  34. if C==4:
  35. if D==0:
  36. s="CD"+s
  37. else:
  38. s="CM"+s
  39. D-=1
  40. else:
  41. s="C"*C+s
  42. s="D"*D+s
  43. s="M"*M+s
  44. return s
  45.  

Explanation:

A normal way to solve this problem. It is a bit faster but a longer code. I check out the special cases only when I=4,X=4,C=4.