Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
Subscribe to see which companies asked this question
class Solution {
int getNum(char c)
{
if (c == 'M')
return 1000;
if (c == 'D')
return 500;
if (c == 'C')
return 100;
if (c == 'L')
return 50;
if (c == 'X')
return 10;
if (c == 'V')
return 5;
if (c == 'I')
return 1;
}
public:
int romanToInt(string s) {
int total = 0;
int curNum = 0;
int preNum = 0;
int count = 0;
for (int i=0; i<s.size(); i++)
{
curNum = getNum(s[i]);
if (curNum == preNum)
{
count++;
total += curNum;
}
else
{
if (preNum != 0 && curNum > preNum)
{
total = total-2*preNum*count;
}
total += curNum;
preNum = curNum;
count = 1;
}
}
return total;
}
};