C++ 13 lines code solution, 30ms~50ms(tests change every time)


  • 0
    H
    class Solution {
    public:
    int romanToInt(string s) {
    	int table[256];
    	table['I'] = 1; table['V'] = 5; table['X'] = 10;table['L'] = 50;table['C'] = 100; table['D'] = 500;table['M'] = 1000;
    	int res = table[s[0]];
    	for(int i = 1; i<s.size(); i++){
    		if(table[s[i]]<=table[s[i-1]]) res += table[s[i]];
    		else  res += table[s[i]]-2*table[s[i-1]];
    	}
    	return res;
    }
    };

Log in to reply
 

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