Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Roman numerals to integers

In data sometimes the same product will be named with a roman numeral while other times it will be a digit.

Example Samsung Galaxy SII verses Samsung Galaxy S2

How can the II be converted to the value 2?

like image 701
Dennis Puzak Avatar asked Feb 15 '13 17:02

Dennis Puzak


People also ask

What is IVX in Roman numerals?

Why is 14 Written in Roman Numerals as XIV? We know that in roman numerals, we write 4 as IV, and 10 as X. Therefore, 14 in roman numerals is written as XIV = X + IV = 10 + 4 = XIV.

What is the Roman numerals 1 to 1000?

List of all perfect cubes from 1 to 1000 are: 1, 8, 27, 64, 125, 216, 343, 512, 729, 1000. Therefore, the list of all perfect cubes in roman numerals between roman numerals 1 to 1000 are: I, VIII, XXVII, LXIV, CXXV, CCXVI, CCCXLIII, DXII, DCCXXIX, M.


Video Answer


1 Answers

I've noticed some really complicated solutions here but this is a really simple problem. I made a solution that avoided the need to hard code the "exceptions" (IV, IX, XL, etc). I used a for loop to look ahead at the next character in the Roman numeral string to see if the number associated with the numeral should be subtracted or added to the total. For simplicity's sake I'm assuming all input is valid.

private static Dictionary<char, int> RomanMap = new Dictionary<char, int>()
    {
        {'I', 1},
        {'V', 5},
        {'X', 10},
        {'L', 50},
        {'C', 100},
        {'D', 500},
        {'M', 1000}
    };

public static int RomanToInteger(string roman)
{
    int number = 0;
    for (int i = 0; i < roman.Length; i++)
    {
        if (i + 1 < roman.Length && RomanMap[roman[i]] < RomanMap[roman[i + 1]])
        {
            number -= RomanMap[roman[i]];
        }
        else
        {
            number += RomanMap[roman[i]];
        }
    }
    return number;
}

I initially tried using a foreach on the string which I think was a slightly more readable solution but I ended up adding every single number and subtracting it twice later if it turned out to be one of the exceptions, which I didn't like. I'll post it here anyway for posterity.

public static int RomanToInteger(string roman)
{
    int number = 0;
    char previousChar = roman[0];
    foreach(char currentChar in roman)
    {
        number += RomanMap[currentChar];
        if(RomanMap[previousChar] < RomanMap[currentChar])
        {
            number -= RomanMap[previousChar] * 2;
        }
        previousChar = currentChar;
    }
    return number;
}
like image 84
David DeMar Avatar answered Oct 05 '22 02:10

David DeMar