【LeetCode】13. Roman to Integer (2 solutions)

时间:2023-12-25 21:33:49

Roman to Integer

Given a roman numeral, convert it to an integer.

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

解法一:非递归

从左到右遍历每个字符,并记录上个字符来处理双字符情况即可。

class Solution {
public:
int romanToInt(string s) {
int n = ;
char lastC = ;
for(int i = ; i < s.size(); i ++)
{
switch(s[i])
{
case 'I':
n += ;
lastC = s[i];
break;
case 'V':
if(lastC == 'I')
{//IV
n -= ;
n += ;
lastC = ;
}
else
{
n += ;
lastC = s[i];
}
break;
case 'X':
if(lastC == 'I')
{//IX
n -= ;
n += ;
lastC = ;
}
else
{
n += ;
lastC = s[i];
}
break;
case 'L':
if(lastC == 'X')
{//XL
n -= ;
n += ;
lastC = ;
}
else
{
n += ;
lastC = s[i];
}
break;
case 'C':
if(lastC == 'X')
{//XC
n -= ;
n += ;
lastC = ;
}
else
{
n += ;
lastC = s[i];
}
break;
case 'D':
if(lastC == 'C')
{//CD
n -= ;
n += ;
lastC = ;
}
else
{
n += ;
lastC = s[i];
}
break;
case 'M':
if(lastC == 'C')
{//CM
n -= ;
n += ;
lastC = ;
}
else
{
n += ;
lastC = s[i];
}
break;
default:
return ;
}
}
return n;
}
};

【LeetCode】13. Roman to Integer (2 solutions)

解法二:递归

处理开头字符情况之后递归处理后续字符串

class Solution {
public:
int romanToInt(string s) {
if(s == "")
return ;
//to here, s.size() >= 1
else if(s[] == 'M')
return + romanToInt(s.substr());
else if(s[] == 'C')
{
if(s.size() == )
//s == "C"
return ;
if(s[] == 'M')
return + romanToInt(s.substr());
else if(s[] == 'D')
return + romanToInt(s.substr());
else
return + romanToInt(s.substr());
}
else if(s[] == 'D')
return + romanToInt(s.substr());
else if(s[] == 'X')
{
if(s.size() == )
//s == "X"
return ;
if(s[] == 'C')
return + romanToInt(s.substr());
else if(s[] == 'L')
return + romanToInt(s.substr());
else
return + romanToInt(s.substr());
}
else if(s[] == 'L')
return + romanToInt(s.substr());
else if(s[] == 'I')
{
if(s.size() == )
//s == "I"
return ;
if(s[] == 'X')
return + romanToInt(s.substr());
else if(s[] == 'V')
return + romanToInt(s.substr());
else
return + romanToInt(s.substr());
}
else if(s[] == 'V')
return + romanToInt(s.substr());
}
};

【LeetCode】13. Roman to Integer (2 solutions)