LeetCode Roman to Integer

 Problem Description Link: https://leetcode.com/problems/roman-to-integer/


Accepted Solution

/*

The solution to the problem is straightforward. You have to find the exceptional numbers, such as 4, 9, 40, 90, 400, and 900, carefully and do simply for the rest.

*/


class Solution {
public:
    int getNum(char ch) {
    if(ch == 'I')
    {
        return 1;
    }
    else if(ch == 'V')
    {
        return 5;
    }
    else if(ch == 'X')
    {
        return 10;
    }
    else if(ch == 'L')
    {
        return 50;
    }
    else if(ch == 'C')
    {
        return 100;
    }
    else if(ch == 'D')
    {
        return 500;
    }
    else if(ch == 'M')
    {
        return 1000;
    }

    return 0;
    }
    int romanToInt(string s) {
       
        string roman = s;

        int i=0, len = roman.length(), num=0;

    for(i=1; i<len; i++)
    {
        //cout << getNum(roman[i]) << " ";
        if(roman[i] == 'V')
        {
            if(roman[i-1] == 'I')
            {
                num += 4;
                roman[i] = 'P';
                roman[i-1] = 'P';
            }
        }
        else if(roman[i] == 'X')
        {
            if(roman[i-1] == 'I')
            {
                num += 9;
                roman[i] = 'P';
                roman[i-1] = 'P';
            }
        }
        else if(roman[i] == 'L')
        {
            if(roman[i-1] == 'X')
            {
                num += 40;
                roman[i] = 'P';
                roman[i-1] = 'P';
            }
        }
        else if(roman[i] == 'C')
        {
            if(roman[i-1] == 'X')
            {
                num += 90;
                roman[i] = 'P';
                roman[i-1] = 'P';
            }
        }
        else if(roman[i] == 'D')
        {
            if(roman[i-1] == 'C')
            {
                num += 400;
                roman[i] = 'P';
                roman[i-1] = 'P';
            }
        }
        else if(roman[i] == 'M')
        {
            if(roman[i-1] == 'C')
            {
                num += 900;
                roman[i] = 'P';
                roman[i-1] = 'P';
            }
        }
    }

    for(i=0; i<len; i++)
    {
        num += getNum(roman[i]);
    }

    return num;
    }
};

Comments

Popular posts from this blog

SPOJ-CMG - Collecting Mango

LightOJ 1009 - Back to Underworld

LeetCode Palindrome Number