Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """
- We traverse the string from right to left, keeping track of the previous numeral’s value to decide whether to add or subtract the current value.
- If the current value is smaller than the previous one, we subtract it; otherwise, we add it to the total.
- """
- class Solution:
- def romanToInt(self, s: str) -> int:
- dict = {'I': 1,'V': 5,'X': 10,'L': 50,'C': 100,'D': 500,'M': 1000}
- ans=0
- prev=0
- for i in reversed(s):
- cur=dict.get(i,0)
- if cur<prev and prev!=0:
- ans-=cur
- else:
- ans+=cur
- prev=cur
- return ans
Advertisement
Add Comment
Please, Sign In to add comment