# [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（罗马数字转换成整数）

Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from ...

## [leetcode]详解Integer to Roman

Integer to RomanRoman与Integer的转换规则？From Wikipedia 现在用的罗马数字由7个字符表示，如下表： 字符 值 I 1 V 5 X...
• CY_TEC
• 2016年06月15日 12:01
• 455

## 【LeetCode with Python】 Integer to Roman

Given an integer, convert it to a roman numeral. Input is guaranteed to be within the range from 1 ...
• nerv3x3
• 2014年07月06日 15:01
• 3519

## LeetCode_Easy心得：13. Roman to Integer （C语言）

13. Roman to Integer
• hhhhhyb
• 2017年07月21日 18:59
• 150

## [LeetCode]Roman to Integer

• jhbxlx
• 2014年01月26日 14:40
• 550

## [LeetCode]12. Integer to Roman(整数转化为罗马数字)

12. Integer to Roman点击查看相关题 罗马数字转化为整数 Given an integer, convert it to a roman numeral. Input is gu...

## leetcode第一刷_Integer to Roman

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