Untitled

mail@pastecode.io avatar
unknown
c_cpp
a month ago
2.9 kB
4
Indexable
Never
int romanToInt(char* s) 
{
    size_t length = strlen(s);
    int result = 0;

    for (int i = 0; i < length; ++i)
    {
        switch (s[i])
        {
            case 'C':
            {
                if (s[i + 1] == 'D')
                {
                    ++i;
                    result += 400;
                    break;
                }
                else if (s[i + 1] == 'M')
                {
                    ++i;
                    result += 900;
                    break;
                }
                else if (s[i + 1] == 'C')
                {
                    ++i;
                    result += 100;

                    if (s[i + 1] == 'C')
                    {
                        ++i;
                        result += 100;
                    }
                }
                result += 100;
                break;
            }
            case 'M':
            {
                result += 1000;
                break;
            }
            case 'D':
            {
                result += 500;
                break;
            }
            case 'X':
            {
                if (s[i + 1] == 'L')
                {
                    ++i;
                    result += 40;
                    break;
                }
                else if (s[i + 1] == 'C')
                {
                    ++i;
                    result += 90;
                    break;
                }
                else if (s[i + 1] == 'X')
                {
                    ++i;
                    result += 10;

                    if (s[i + 1] == 'X')
                    {
                        ++i;
                        result += 10;
                    }
                }
                result += 10;
                break;
            }
            case 'L':
            {
                result += 50;
                break;
            }
            case 'I':
            {
                if (s[i + 1] == 'V')
                {
                    ++i;
                    result += 4;
                    break;
                }
                else if (s[i + 1] == 'X')
                {
                    ++i;
                    result += 9;
                    break;
                }
                else if (s[i + 1] == 'I')
                {
                    ++i;
                    result++;

                    if (s[i + 1] == 'I')
                    {
                        ++i;
                        result++;
                    }
                }
                result++;
                break;
            }
            case 'V':
            {
                result += 5;
                break;
            }
        }
    }

    return result;
}
Leave a Comment