题意:就是将罗马数字转化为十进制整数
罗马数字表
字符 数值
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
一般大的数字在小的左边,如果大的数字在小的右边,则数值是相减的结果
比如IV表示4,即5 - 1 = 4
class Solution {
public:
int romanToInt(string s) {
int len = s.length();
if(len == 0)
return 0;
map<char, int>m;
int res = 0;
//建立映射关系
m['I'] = 1;
m['V'] = 5;
m['X'] = 10;
m['L'] = 50;
m['C'] = 100;
m['D'] = 500;
m['M'] = 1000;
for(int i = 0; i < len; )
{
if(i + 1 < len && m[s[i]] < m[s[i+1]])
{
//如果大的数字在小的右边
res += ( m[s[i+1]] - m[s[i]] );
i += 2;
}
else
{
res += m[s[i]];
i++;
}
}
return res;
}
};
用map容器插入数据要时间,可以用switch获得 每个字符的值,更快一点点
class Solution {
public:
int romanToInt(string s) {
int len = s.length();
if(len == 0)
return 0;
int res = 0;
for(int i = 0; i < len; )
{
if(i + 1 < len && getValue(s[i]) < getValue(s[i+1]))
{
//如果大的数字在小的右边
res += ( getValue(s[i+1]) - getValue(s[i]) );
i += 2;
}
else
{
res += getValue(s[i]);
i++;
}
}
return res;
}
int getValue(char x)
{
switch(x){
case 'I':
return 1;
case 'V':
return 5;
case 'X':
return 10;
case 'L':
return 50;
case 'C':
return 100;
case 'D':
return 500;
case 'M':
return 1000;
}
}
};