Roman to Integer
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
Solution:
一种很粗暴的解法,罗列所有可能出现的情况:
class Solution {
public:
int romanToInt(string s) {
int total = 0;
for (int a = 0; a < s.length(); a++)
{
if (s[a] == 'I')
{
if (s[a+1] == 'V')
{
total += 4;
a++;
}
else if (s[a+1] == 'X')
{
total += 9;
a++;
}
else
{
total += 1;
}
}
else if (s[a] == 'X')
{
if (s[a+1] == 'L')
{
total += 40;
a++;
}
else if (s[a+1] == 'C')
{
total += 90;
a++;
}
else
{
total += 10;
}
}
else if (s[a] == 'C')
{
if (s[a+1] == 'D')
{
total += 400;
a++;
}
else if (s[a+1] == 'M')
{
total += 900;
a++;
}
else
{
total += 100;
}
}
else if (s[a] == 'V') total += 5;
else if (s[a] == 'L') total += 50;
else if (s[a] == 'D') total += 500;
else if (s[a] == 'M') total += 1000;
}
return total;
}
};