C++


  • 0
    Y

    class Solution {
    public:
    int romanToInt(string s) {
    int result = 0;
    int len = s.size();
    char* c[4][10] = {
    { "", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX" },
    { "", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC" },
    { "", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM" },
    { "", "M", "MM", "MMM", }
    };

    	string tmp = s;
    	for (int j = 0; j < 3 && len > 0; j++)
    	{
    		for (int i = 9; i > 0 && len > 0; i--)
    		{
    			int tmplen = strlen(c[j][i]);
    			if (len >= tmplen && tmp.substr(len - tmplen, tmplen) == c[j][i])
    			{
    				if (	len <= 1 
    					|| tmp.substr(len - 2, 2) != "IV"
    					&&	tmp.substr(len - 2, 2) != "XL" 
    					&&	tmp.substr(len - 2, 2) != "CD")
    				{
    					result = i*pow(10, j) + result;
    					tmp = tmp.substr(0, len - tmplen);
    					len = tmp.size();
    					break;
    				}
    				else
    				{
    					result = (i-1)*pow(10, j) + result;
    					tmp = tmp.substr(0, len - 2);
    					len = tmp.size();
    					break;
    				}
    				
    			}
    		}
    	}
    
    	if (tmp == "M")		return result + 1000;
    	if (tmp == "MM")	return result + 2000;
    	if (tmp == "MMM")	return result + 3000;
    	return result;
    }
    

    };


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.