# C++ Solution

• Take symbol one by one from starting from index 0:
If the current value of the symbol is greater than or equal to the value of next symbol, then add this value to the running total.
else subtract this value by adding the value of next symbol to the running total.

``````class Solution {
public:
int romanToInt(string &s)
{
int result = 0;

for(int i = 0; i <s.length();i++)
{
// get value of s[i]
int s1 = value(s[i]);

if(i+1 < s.length())
{
// get value s[i+1]
int s2 = value(s[i+1]);
if(s1 >= s2)
{
// value of current symbol is >= to next symbol
result = result + s1;
}
else
{
// value of current symbol is < than next symbol
result = result + s2 - s1;
i++;
}
}
else
{
result = result + s1;
i++;
}
}
return result;
}

int value(char r)
{
if (r == 'I')
return 1;
if (r == 'V')
return 5;
if (r == 'X')
return 10;
if (r == 'L')
return 50;
if (r == 'C')
return 100;
if (r == 'D')
return 500;
if (r == 'M')
return 1000;

return -1;
}
};

``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.