这题主要考虑几个特殊情况。
C语音版本
int romanToInt(char* s) {
int sum;
int len = strlen(s);
for (int i = 0; i<len ; i++)
{
if(s[i]=='C')
{
if(s[i+1]=='D')
{
sum = sum + 400;
i++;
}
else if(s[i+1] == 'M')
{
sum =sum +900;
i++;
}
else
{
sum = sum + 100;
}
}
else if(s[i]=='X')
{
if(s[i+1]=='L')
{
sum = sum + 40;
i++;
}
else if(s[i+1] == 'C')
{
sum =sum +90;
i++;
}
else
{
sum = sum + 10;
}
}
else if(s[i]=='I')
{
if(s[i+1]=='V')
{
sum = sum + 4;
i++;
}
else if(s[i+1] == 'X')
{
sum =sum +9;
i++;
}
else
{
sum = sum + 1;
}
}
else if(s[i]=='V')
{
sum = sum + 5;
}
else if(s[i]=='L')
{
sum = sum + 50;
}
else if(s[i]=='D')
{
sum = sum + 500;
}
else if(s[i]=='M')
{
sum = sum + 1000;
}
}
return sum;
}
别人的C语音版本
int num(char s) {
if (s == 'I') return 1;
else if (s == 'V') return 5;
else if (s == 'X') return 10;
else if (s == 'L') return 50;
else if (s == 'C') return 100;
else if (s == 'D') return 500;
else if (s == 'M') return 1000;
else return 0;
}
int romanToInt(char* s) {
int sum = 0;
int last = 0;
if (*s != 0) {
last = num(*s++);
}
while (*s != 0) {
int n = num(*s);
if (n > last) {
sum -= last;
} else {
sum += last;
}
last = n;
s++;
}
sum += last;
return sum;
}
C++版本
class Solution {
public:
int romanToInt(string s) {
int sum = 0;
unordered_map<char,int> m{{'I',1},{'V',5},{'X',10},{'L',50},{'C',100},{'D',500},{'M',1000}};
for(int i = 0; i<s.size(); i++)
{
int val = m[s[i]];
if(i == s.size() - 1||m[s[i+1]]<=m[s[i]])
{
sum = sum + val;
}
else sum = sum - val;
}
return sum;
}
};