13. 罗马数字转整数
这道题目和上一道题目是相反的转换,上一道题目中整数转罗马数字是把整数拆分成每一位,利用罗马数字表示规则从高位到低位拼接即可。那么罗马数字转整数也是一样的道理,从高位到低位(从左到右)拆分每一位整数对应的罗马字符串,然后将每一位整数相加就可以了。
例如:
“XXVII”代表27,那么需要把“XXVII”拆分成20和7,从左往右“XX”对应20,VII对应7,则“XXVII”对应的整数值为20 + 7,即27。
通过例子可以看出来,解题思路很简单,就是识别每一位整数对应的罗马字符串,最后相加就好了。
具体算法为:从左往右遍历每一个罗马字符,分离出整数每一位的值,算法的复杂度为O(n)。
class Solution {
public:
int romanToInt(string s) {
const int len = s.size();
int n = 0;
for(int i = 0; i < len;)
{
int num = 0;
char c = s[i];
int nextIndex = i + 1;
if(c == 'I')
{
num = 1;
while(nextIndex < len)
{
char nextChar = s[nextIndex];
if(nextChar == 'V')
{
num = 4;
}
else if(nextChar == 'X')
{
num = 9;
}
else if(nextChar == 'I')
{
num += 1;
}
else
{
break;
}
nextIndex++;
}
}
else if( c == 'V')
{
num = 5;
while(nextIndex < len)
{
char nextChar = s[nextIndex];
if(nextChar == 'I')
{
num += 1;
}
else
{
break;
}
nextIndex++;
}
}
else if(c == 'X')
{
num = 10;
while(nextIndex < len)
{
char nextChar = s[nextIndex];
if(nextChar == 'X')
{
num += 10;
}
else if(nextChar == 'L')
{
num = 40;
}
else if(nextChar == 'C')
{
num = 90;
}
else
{
break;
}
nextIndex++;
}
}
else if(c == 'L')
{
num = 50;
while(nextIndex < len)
{
char nextChar = s[nextIndex];
if(nextChar == 'X')
{
num += 10;
}
else
{
break;
}
nextIndex++;
}
}
else if(c == 'C')
{
num = 100;
while(nextIndex < len)
{
char nextChar = s[nextIndex];
if(nextChar == 'C')
{
num += 100;
}
else if(nextChar == 'D')
{
num = 400;
}
else if(nextChar == 'M')
{
num = 900;
}
else
{
break;
}
nextIndex++;
}
}
else if(c == 'D')
{
num = 500;
char nextChar = s[nextIndex];
while(nextIndex < len)
{
if(nextIndex == 'C')
{
num += 100;
}
else
{
break;
}
nextIndex++;
}
}
else if(c == 'M')
{
num = 1000;
while(nextIndex < len)
{
char nextChar = s[nextIndex];
if(nextChar == 'M')
{
num += 1000;
}
else
{
break;
}
nextIndex++;
}
}
i = nextIndex;
n += num;
}
return n;
}
};