# C++ wiki definition translation

• Definition

``````Symbol	Value
I	1
V	5
X	10
L	50
C	100
D	500
M	1,000

I placed before V or X indicates one less, so four is IV (one less than five) and nine is IX (one less than ten)
X placed before L or C indicates ten less, so forty is XL (ten less than fifty) and ninety is XC (ten less than a hundred)
C placed before D or M indicates a hundred less, so four hundred is CD (a hundred less than five hundred) and nine hundred is CM (a hundred less than a thousand)
``````

I know this is not a clever one like most people come up with, only a straightforward translation to share.

Code

``````class Solution {
public:
int romanToInt(string s) {
int ans = 0;
for(int i = 0; i < s.size(); i++){
if(s[i] == 'M') ans += 1000;
else if(s[i] == 'D') ans += 500;
else if(s[i] == 'C') {
int sign = 1 - (i < s.size() - 1 && (s[i + 1] == 'D' || s[i + 1] == 'M')) * 2;
ans += sign * 100;
}
else if(s[i] == 'L') ans += 50;
else if(s[i] == 'X') {
int sign = 1 - (i < s.size() - 1 && (s[i + 1] == 'L' || s[i + 1] == 'C')) * 2;
ans += sign * 10;
}
else if(s[i] == 'V') ans += 5;
else {
int sign = 1 - (i < s.size() - 1 && (s[i + 1] == 'V' || s[i + 1] == 'X')) * 2;
ans += sign * 1;
}
}

return ans;
}
};``````

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