# [LeetCode] Roman to Integer

class Solution {
public:
int romanToInt(string s) {
map<char,int> m={{'M',1000},{'D',500},{'C',100},{'L',50},{'X',10},{'V',5},{'I',1}};
int out=0,i;
if(s.size()==1) return m[s[0]];
out += m[s[0]];
for(i = 1; i != s.size(); ++i){
if(m[s[i]]<=m[s[i-1]])
out+=m[s[i]];
else
out = out -2*m[s[i-1]] +m[s[i]];
}
return out;

}
};

c语言同样的思路

int romanToInt(char *s) {
#define _M 1000
#define _D 500
#define _C 100
#define _L 50
#define _X 10
#define _V 5
#define _I 1

int result  = 0;
int i;
int last = _M;
for(i = 0;i < strlen(s);i++)
{
switch (s[i])
{
case 'M':
result = (last >= _M ? result + _M:result + _M - (last << 1));
last = _M;
break;
case 'D':
result = (last >= _D ? result + _D:result + _D - (last << 1));
last = _D;
break;
case 'C':
result = (last >= _C ? result + _C:result + _C - (last << 1));
last = _C;
break;
case 'L':
result = (last >= _L ? result + _L:result + _L - (last << 1));
last = _L;
break;
case 'X':
result = (last >= _X ? result + _X:result + _X - (last << 1));
last = _X;
break;
case 'V':
result = (last >= _V ? result + _V:result + _V - (last << 1));
last = _V;
break;
case 'I':
result = (last >= _I ? result + _I:result + _I - (last << 1));
last = _I;
break;
}

}
return result;
}

• 本文已收录于以下专栏：

举报原因： 您举报文章：[LeetCode] Roman to Integer 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)