imashutosh51

Integer to Roman

Feb 26th, 2026
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.71 KB | None | 0 0
  1. """
  2. Use a greedy approach by iterating over Roman values from largest to smallest, repeatedly subtracting the biggest possible value and appending its symbol.
  3. Subtractive cases like 4 (IV), 9 (IX), 40 (XL), etc., are pre-stored in the mapping to naturally handle special Roman numeral rules.
  4. """
  5. class Solution:
  6.     def intToRoman(self, num: int) -> str:
  7.         dict = {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'}
  8.         print(dict)
  9.         ans=''
  10.         while num>0:
  11.             for i in dict.keys():
  12.                 if i<=num:
  13.                     ans+=dict[i]
  14.                     num-=i
  15.                     break
  16.         return ans
  17.  
  18.  
  19.        
Advertisement
Add Comment
Please, Sign In to add comment