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
要先了解罗马数字转换成阿拉伯数的规则。查一下就找到了...不详细说了。
class Solution {
public:
int romanToInt(string s) {
int ans = 0;
int pre = -1;
for( int i = s.size() - 1; i >= 0; i-- ) {
int cur = caculate( s[i] );
if( cur >= pre ) ans = ans + cur;
else ans = ans - cur;
pre = cur;
}
return ans;
}
int caculate( char ch ) {
int res = 0;
switch( ch ) {
case 'I': res = 1; break;
case 'V': res = 5; break;
case 'X': res = 10; break;
case 'L': res = 50; break;
case 'C': res = 100; break;
case 'D': res = 500; break;
case 'M': res = 1000; break;
}
return res;
}
};