Total Accepted: 60723
Total Submissions: 168485
Difficulty: Easy
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
Subscribe to see which companies asked this question
Hide Similar Problems
code:
/*
I:1
V:5
X:10
L:50
C:100
D:500
M:1000
*/
class Solution {
public:
int getInt(char c) {
switch(c){
case 'I':
return 1;
case 'V':
return 5;
case 'X':
return 10;
case 'L':
return 50;
case 'C':
return 100;
case 'D':
return 500;
case 'M':
return 1000;
}
}
int romanToInt(string s) {
int len = s.size();
int ret = 0;
for(int i=0;i<len;i++) {
if(i>0 && getInt(s[i]) > getInt(s[i-1]))
ret += (getInt(s[i]) - 2 * getInt(s[i-1]));
else
ret += getInt(s[i]);
}
return ret;
}
};