Monday, September 16, 2013

[Leetcode] Roman to Integer


Given a roman numeral, convert it to an integer.

Input is guaranteed to be within the range from 1 to 3999.

Analysis:

IV, IX, XL, XC, XD, CM could be summarized as m[s[i+1]]-m[s[i]].

int romanToInt(string s) {
    map m;
    m['I'] = 1;
    m['V'] = 5;
    m['X'] = 10;
    m['L'] = 50;
    m['C'] = 100;
    m['D'] = 500;
    m['M'] = 1000;
    
    int i=0; 
    int ret = 0;
    while(i < s.size())
    {
        if ((s[i] == 'I' && i + 1 < s.size() && (s[i+1] == 'V' || s[i+1] == 'X')) ||
            (s[i] == 'X' && i + 1 < s.size() && (s[i+1] == 'L' || s[i+1] == 'C')) ||
            (s[i] == 'C' && i + 1 < s.size() && (s[i+1] == 'D' || s[i+1] == 'M')))
        {
            ret = ret + (m[s[i+1]] - m[s[i]]);
            i = i+2;
        }
        else
        {
            ret = ret + m[s[i]];
            i = i + 1;
        }    
    }
    return ret;
}

No comments:

Post a Comment