43. Roman to Integer
13 Jul 2020 | Daily Algorithms
class Solution {
public:
int romanToInt(string s) {
int res =0;
int temp = 0;
for(int i = 0; i<s.size(); i++)
{
char sym = s[i];
int pos = 0;
switch(sym)
{
case 'I': pos = 1; break;
case 'V': pos = 5; break;
case 'X': pos = 10; break;
case 'L': pos = 50; break;
case 'C': pos = 100; break;
case 'D': pos = 500; break;
case 'M': pos = 1000; break;
default : return 0;
}
res += pos;
if(temp<pos)
{
res -= 2*temp;
}
temp = pos;
}
return res;
}
};
class Solution {
public:
int romanToInt(string s) {
int res =0;
int temp = 0;
for(int i = 0; i<s.size(); i++)
{
char sym = s[i];
int pos = 0;
switch(sym)
{
case 'I': pos = 1; break;
case 'V': pos = 5; break;
case 'X': pos = 10; break;
case 'L': pos = 50; break;
case 'C': pos = 100; break;
case 'D': pos = 500; break;
case 'M': pos = 1000; break;
default : return 0;
}
res += pos;
if(temp<pos)
{
res -= 2*temp;
}
temp = pos;
}
return res;
}
};
Comments