Roman to Integer

Given a Roman numeral, Write a code to convert roman to integer value.

Roman numerals are represented by seven different letters (I, V, X, L, C, D, M). These seven letters are used to make thousands of numbers.

Roman Numerals Symbol and It's decimal value.

For example –

Example 1 –

Input  : II , Output : 2

Example 2 –

Input  : XI , Output : 11

Example 3 – 

Input  : IV , Output : 4

Example 4 – 

Input : LVII , Output: 57 

NOTE : The given input is guaranteed to be within the range from 1 to 3999.

Convert roman to integer

Programming video tutorials

Programming Questions on Arrays

Programming Questions on Linked List

Programming Questions on String

We have discussed the problem statement. In this problem, we have to convert the roman number to an integer.

Convert Roman to Integer Value – Java Code

Before solving this problem, Let’s understand a few important points about Roman Numerals.

Roman numerals are usually written from largest to smallest from left to right. For example – XII (12), VII (7), LVII (57), etc.

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 we need to do subtraction.

  • 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.

Keeping these points in mind, here are the following steps to solve this problem.

  1. Traverse a string and pick one roman numeral (each character) at a time.
  2. Convert each symbol of Roman Numeral into the value it represents.
  3. If current value of numeral is greater than or equal to the value of next numeral, then add this value to the running total. Else subtract this value from the result.

The time complexity of this approach is O(n) and its space complexity is O(1).

convert roman numerals to numbers in java video tutorial

Roman to Integer InterviewBit Solution

Tagged , , . Bookmark the permalink.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.