Easy to understand C++ implement in 36ms


  • 0
    L
    class Solution {
    public:
        int romanToInt(string s) {
            int result=0;
    		int lastone = 0;
    
    		for (size_t i = 0; i < s.size(); i++)
    		{
    			int temp;
    			switch (s[i])
    			{
    			case'I':temp = 1; break;
    			case'V':temp = 5; break;
    			case'X':temp = 10; break;
    			case'L':temp = 50; break;
    			case'C':temp = 100; break;
    			case'D':temp = 500; break;
    			case'M':temp = 1000; break;
    			default:
    				break;
    			}
    			if (lastone<temp)
    			{
    				result += temp - 2*lastone;
    			}
    			else
    			{
    				result += temp;				
    			}
    			lastone = temp;
    		}
    		return result;
        }
    };

Log in to reply
 

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