Roman to Integer:
题目:
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
解法(C++):
class Solution {
private:
int mean(char c)
{
int data = 0;
switch(c)
{
case 'I':data = 1;break;
case 'V':data = 5;break;
case 'X':data = 10;break;
case 'L':data = 50;break;
case 'C':data = 100;break;
case 'D':data = 500;break;
case 'M':data = 1000;break;
}
return data;
}
public:
int romanToInt(string s) {
int result = 0;
int n = s.size();
result += mean(s.at(0));
for(int i = 1; i < n; i++)
{
int pre = mean(s.at(i - 1));
int cur = mean(s.at(i));
if(pre >= cur)
{
result += cur;
}
else
{
result += (cur - 2 * pre);
}
}
return result;
}
};
【注】switch一定要加break