How to convert a Roman number to an integer in Python

1 Answer

0 votes
# Roman numeral to integer conversion in Python

roman_map = {
    'I': 1,
    'V': 5,
    'X': 10,
    'L': 50,
    'C': 100,
    'D': 500,
    'M': 1000
}

def roman_to_int(s: str) -> int:
    total = 0
    prev_value = 0

    for ch in reversed(s):
        current_value = roman_map[ch]
        if current_value < prev_value:
            total -= current_value
        else:
            total += current_value
        prev_value = current_value

    return total


if __name__ == "__main__":
    roman = "XCVII"
    result = roman_to_int(roman)
    print(f"The integer value of {roman} is {result}")


'''
XCVII =
XC+V+I+I =
90+5+1+1 =
97
'''


'''
run:

The integer value of XCVII is 97

'''

 



answered Dec 3, 2025 by avibootz
...