Clean O(n) C++ solution


  • 0
    B
    int romanToInt(string s) {
    	int val[] = { 1000,500,100,50,10,5,1 };
    	char sym[] = { 'M', 'D', 'C', 'L', 'X', 'V', 'I' };
    	map<char, int> Map = { {'M',1000} , {'D', 500}, {'C', 100}, {'L', 50}, {'X',10},{'V',5},{'I',1} };
    	int ret = 0;
    	if (s.size() == 1)
    	{
    		ret += Map[s[0]];
    	}
    	else if(s.size() > 1)
    	{
    		int i = 1;
    		int cur = Map[s[0]];
    		while (i < s.size())
    		{
    			if (cur < Map[s[i]])
    			{
    				ret -= cur;
    			}
    			else
    			{
    				ret += cur;
    			}
    			cur = Map[s[i++]];
    		}
    		ret += cur;
    	}
    	return ret;
    }
    

Log in to reply
 

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