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 numerals, just two ones are 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 from 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 beforeV
(5) andX
(10) to make 4 and 9.X
can be placed beforeL
(50) andC
(100) to make 40 and 90.C
can be placed beforeD
(500) andM
(1000) to make 400 and 900.
Given a Roman numeral, convert it to an integer.
Ashutosh Kumar Verma
14-Jun-2024Roman to Integer Converter
Here is a simple example to convert the Roman number into an Integer,
In the above example-
Dictionary- We create a
romanToValue
dictionary that maps Roman numeric characters to their corresponding integer values.Variables- We initialize
total
to 0 to store the last one andprevValue
0 to check the value of the previous number in iteration.Iteration- Iterate over each character of the input string
s
.Logic-
For each character, we get its value from the dictionary.
If the current value is greater than the previous value, it indicates an omitted combination (such as IV or IX). In this case, we add the current value and subtract twice the previous value (because we added it once before).
Otherwise, we will simply add the current value to the total.
We update the
prevValue
to the current value for the next iteration.Output-
Also, Read: Prime Number Checker