Problem

Given a roman numeral, convert it to an integer.

Input is guaranteed to be within the range from 1 to 3999.

Ideas

Finding the Law of Changing Roman Numbers into Arabic Numbers。

Solution

[code lang=”cpp”]
class Solution {
public:
int romanToInt(string s) {
int l = s.length(), a = 0;
for (int i = 0; i < l; ++i) {
if (i < l – 1 && char2int(s[i]) < char2int(s[i + 1])) {
a -= char2int(s[i]);
} else {
a += char2int(s[i]);
}
}
return a;
}
int char2int(char c) {
switch (c) {
case ‘I’:
return 1;
break;
case ‘V’:
return 5;
break;
case ‘X’:
return 10;
break;
case ‘L’:
return 50;
break;
case ‘C’:
return 100;
break;
case ‘D’:
return 500;
break;
case ‘M’:
return 1000;
break;
default:
return 0;
break;
}
}
};
[/code]


文章来源:胡小旭 => [LeetCode]Roman to Integer

Share:

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.