Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- '''
- Following is the list of Roman symbols which include subtractive cases also:
- SYMBOL VALUE
- I 1
- IV 4
- V 5
- IX 9
- X 10
- XL 40
- L 50
- XC 90
- C 100
- CD 400
- D 500
- CM 900
- M 1000
- 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.
- '''
- class Solution:
- def intToRoman(self, num: int) -> str:
- 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'}
- res=""
- for val,sym in d.items():#dictionary should store the order perfectly or else use simplelist
- count,num=divmod(num,val)
- if count:res+=(sym*count)
- return res
- #Roman to Integer:
- class Solution:
- def romanToInt(self, s: str) -> int:
- d={'L':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000,'I':1}
- n=len(s)
- sum=d[s[-1]]
- for i in range(n-2,-1,-1):
- if d[s[i]]<d[s[i+1]]:sum-=d[s[i]] #If order breaks substract
- else:sum+=d[s[i]]#else add
- return sum
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement