Roman to Integer (13)
Roman numerals are represented by seven different symbols: I
, V
, X
, L
, C
, D
and M
. Given a roman numeral, convert it to an integer.
Approach:
Iterate through given roman number from left to right.
Initialize result = 0.
Take one character at a time and check its corresponding numeral from the table and add it to the result.
The only special case that needs to be considered is when the character at left has smaller value than the character at right. for example ‘IX’ for 9 or ‘IV’ for 4, in such cases, add the difference of right character value and left to the result. Except for this special case, In all other cases, all the pairs have left character value >= right character value.
Complexity: O(N) time.
Last updated
Was this helpful?