imashutosh51

Roman to Integer

Feb 26th, 2026
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.65 KB | None | 0 0
  1. """
  2. 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.
  3. If the current value is smaller than the previous one, we subtract it; otherwise, we add it to the total.
  4. """
  5. class Solution:
  6.     def romanToInt(self, s: str) -> int:
  7.         dict = {'I': 1,'V': 5,'X': 10,'L': 50,'C': 100,'D': 500,'M': 1000}
  8.         ans=0
  9.         prev=0
  10.         for i in reversed(s):
  11.             cur=dict.get(i,0)
  12.             if cur<prev and prev!=0:
  13.                 ans-=cur
  14.             else:
  15.                 ans+=cur
  16.             prev=cur
  17.         return ans
  18.        
  19.        
Advertisement
Add Comment
Please, Sign In to add comment