Roman to Integer

🏠 ⬅️ ➡️

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.

Example 1:

Input: s = "III " Output: 3 Explanation: III = 3.

Example 2:

Input: s = "LVIII " Output: 58 Explanation: L = 50, V= 5, III = 3.

Example 3:

Input: s = "MCMXCIV " Output: 1994 Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.

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

Note: This problem is from LeetCode.
Compiled
Executed
Correct
program main
    implicit none

    character(len=10), parameter :: I = "I", V = "V", X = "X", L = "L", &
                                     C = "C", D = "D", M = "M"
    character(len=*) :: s
    integer :: n

    call get_command_argument(1, s)
    read(s, *) n

    write(*, "(A)", advance="no") decode(n)

contains

    function decode(n) result(roman)
        implicit none
        integer, intent(in) :: n
        character(len=:), allocatable :: roman

        if (n == 1) then
            allocate(character(len=1) :: roman)
            roman = I
        else if (n == 5) then
            allocate(character(len=1) :: roman)
            roman = V
        else if (n == 10) then
            allocate(character(len=1) :: roman)
            roman = X
        else if (n == 50) then
            allocate(character(len=1) :: roman)
            roman = L
        else if (n == 100) then
            allocate(character(len=1) :: roman)
            roman = C
        else if (n == 500) then
            allocate(character(len=1) :: roman)
            roman = D
        else if (n == 1000) then
            allocate(character(len=1) :: roman)
            roman = M
        else if (n > 1000) then
            allocate(character(len=len(decode(n / 1000))+1) :: roman)
            roman = decode(n / 1000) // M
            n = mod(n, 1000)
            if (n > 0) then
                allocate(character(len=len(roman)+len(decode(n))) :: roman)
                roman = roman // decode(n)
            end if
        end if
    end function decode
end program main
Compiled
Executed
Correct
PROGRAM ROMAN_TO_INTEGER

IMPLICIT NONE

CHARACTER(LEN=15) :: s
INTEGER :: i, j, value

! Read input
READ(*,*) s

! Initialize variables
i = 1
j = 1
value = 0

! Loop through the input string
DO WHILE (i <= LEN(s))

    ! Check for valid characters
    IF (s(i:i) /= "I" .AND. s(i:i) /= "V" .AND. s(i:i) /= "X" .AND. &
        s(i:i) /= "L" .AND. s(i:i) /= "C" .AND. s(i:i) /= "D" .AND. &
        s(i:i) /= "M") THEN
        PRINT *, "Invalid input"
        STOP
    END IF

    ! Check for subtraction
    IF (s(i:i+1) == "IV" .OR. s(i:i+1) == "IX" .OR. s(i:i+1) == "XL" .OR. &
        s(i:i+1) == "XC" .OR. s(i:i+1) == "CD" .OR. s(i:i+1) == "CM") THEN
        value = value - (10 ** (j-1))
        i = i + 2
        j = j + 1
    ELSE
        ! Check for addition
        IF (s(i:i+1) == "II" .OR. s(i:i+1) == "XX" .OR. s(i:i+1) == "XXX" .OR. &
            s(i:i+1) == "CCC" .OR. s(i:i+1) == "DDD" .OR. s(i:i+1) == "MMM") THEN
            value = value + (10 ** (j-1))
            i = i + 2
            j = j + 1
        ELSE
            ! Check for single digit
            IF (s(i:i) == "I") THEN
                value = value + 1
                i = i + 1
                j = j + 1
            ELSE IF (s(i:i) == "V") THEN
                value = value + 5
                i = i + 1
                j = j + 1
            ELSE IF (s(i:i) == "X") THEN
                value = value + 10
                i = i + 1
                j = j + 1
            ELSE IF (s(i:i) == "L") THEN
                value = value + 50
                i = i + 1
                j = j + 1
            ELSE IF (s(i:i) == "C") THEN
                value = value + 100
                i = i + 1
                j = j + 1
            ELSE IF (s(i:i) == "D") THEN
                value = value + 500
                i = i + 1
                j = j + 1
            ELSE IF (s(i:i) == "M") THEN
                value = value + 1000
                i = i + 1
                j = j + 1
            END IF
        END IF
    END IF

END DO

! Print output
PRINT *, value

END PROGRAM ROMAN_TO_INTEGER
🌐 Data from online sources
def roman_to_int(s):
    roman_values = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
    total = 0
    prev_value = 0

    for c in s:
        current_value = roman_values[c]
        if current_value > prev_value:
            total += current_value - 2 * prev_value
        else:
            total += current_value
        prev_value = current_value

    return total
The algorithm iterates through the input string, which represents the Roman numeral. At each iteration, the character is converted to its corresponding integer value using a hash map. Then, the value is added to the total. However, if the current value is greater than the previous value, it means that we need to subtract the previous value from the current value (while considering that the previous value has already been added once). To do this, we add to the total the current value minus 2 times the previous value. Finally, the previous value is updated, and the loop continues. After the loop finishes, the total gives us the integer value equivalent to the Roman numeral.
🌐 Data from online sources
int romanToInt(string s) {
    unordered_map<char, int> roman_values = { {'I', 1}, {'V', 5}, {'X', 10}, {'L', 50}, {'C', 100}, {'D', 500}, {'M', 1000} };
    int total = 0;
    int prev_value = 0;

    for (char c : s) {
        int current_value = roman_values[c];
        if (current_value > prev_value)
            total += current_value - (2 * prev_value);
        else
            total += current_value;
        prev_value = current_value;
    }

    return total;
}
The algorithm iterates through the input string, which represents the Roman numeral. At each iteration, the character is converted to its corresponding integer value using a hash map. Then, the value is added to the total. However, if the current value is greater than the previous value, it means that we need to subtract the previous value from the current value (while considering that the previous value has already been added once). To do this, we add to the total the current value minus 2 times the previous value. Finally, the previous value is updated, and the loop continues. After the loop finishes, the total gives us the integer value equivalent to the Roman numeral.