Roman To Integer Leetcode Solution

Roman To Integer Leetcode Problem :

Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.

Symbol       Value
I             1
V             5
X             10
L             50
C             100
D             500
M             1000

For example, 2 is written as II in Roman numeral, just two ones added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II.

Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:

  • I can be placed before V (5) and X (10) to make 4 and 9.
  • X can be placed before L (50) and C (100) to make 40 and 90.
  • C can be placed before D (500) and M (1000) to make 400 and 900.

Given a roman numeral, convert it to an integer.

roman number

Roman To Integer Leetcode Solution :

Constraints :

  • 1 <= s.length <= 15
  • s contains only the characters (‘I’, ‘V’, ‘X’, ‘L’, ‘C’, ‘D’, ‘M’).
  • It is guaranteed that s is a valid roman numeral in the range [1, 3999].

Example 1:

  • Input: s = “LVIII”
  • Output: 58
  • Explanation: L = 50, V= 5, III = 3.,/li>

    Example 2:

  • Input: s = “MCMXCIV”
  • Output: 1994
  • Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
  • Constraints:
    • The length of the string is between 1 and 15.
    • The String contain only I, V, X, L, C, D, M characters.
    • The String is a valid roman numeral.

Intuition :

The key intuition lies in the fact that in Roman numerals, when a smaller value appears before a larger value, it represents subtraction, while when a smaller value appears after or equal to a larger value, it represents addition.

Approach :
  1. The unordered map m is created and initialized with mappings between Roman numeral characters and their corresponding integer values. For example, ‘I’ is mapped to 1, ‘V’ to 5, ‘X’ to 10, and so on.
  2. The variable ans is initialized to 0. This variable will accumulate the final integer value of the Roman numeral string.
  3. The for loop iterates over each character in the input string s.
roman to integer leetcode

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Code :

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription