Advertisement
Iam_Sandeep

Roman to Integer and Integer to Roman

Jul 24th, 2022
1,026
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.41 KB | None | 0 0
  1. '''
  2. Following is the list of Roman symbols which include subtractive cases also:
  3.  
  4. SYMBOL       VALUE
  5. I             1
  6. IV            4
  7. V             5
  8. IX            9
  9. X             10
  10. XL            40
  11. L             50
  12. XC            90
  13. C             100
  14. CD            400
  15. D             500
  16. CM            900
  17. M             1000      
  18. Idea is to convert the units, tens, hundreds, and thousands places of the given number separately. If the digit is 0, then there's no corresponding Roman numeral symbol. The conversion of digit's 4's and 9's are little bit different from other digits because these digits follows subtractive notation.
  19. '''
  20. class Solution:
  21.     def intToRoman(self, num: int) -> str:
  22.         d = {1000: 'M', 900: 'CM', 500: 'D', 400: 'CD', 100: 'C', 90: 'XC', 50: 'L', 40: 'XL', 10: 'X', 9: 'IX', 5: 'V', 4: 'IV', 1: 'I'}  
  23.         res=""
  24.         for val,sym in d.items():#dictionary should store the order perfectly or else use simplelist
  25.             count,num=divmod(num,val)
  26.             if count:res+=(sym*count)
  27.         return res
  28.    
  29. #Roman to Integer:
  30. class Solution:
  31.     def romanToInt(self, s: str) -> int:
  32.         d={'L':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000,'I':1}
  33.         n=len(s)
  34.         sum=d[s[-1]]
  35.         for i in range(n-2,-1,-1):
  36.             if d[s[i]]<d[s[i+1]]:sum-=d[s[i]] #If order breaks substract
  37.             else:sum+=d[s[i]]#else add
  38.         return sum
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement