13. Roman to Integer
Description
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
Solution
水题……
只要知道罗马数字符号对应的整数就好了,唯一要注意的是以4开头的表示,比如4是IV。所以需要做一个判断,如果s[i-1]< s[i],说明是特殊情况,result赋值的时候+=(s[i] - 2*s[i-1])
Complexity analysis
遍历一次给出的string,O(N)
Code
class Solution {
public:
int trans(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;
}
return 0;
}
int romanToInt(string s) {
int result = trans(s[0]);
for (int i = 1; i < s.length(); i++) {
if (trans(s[i - 1]) < trans(s[i])) {
result += trans(s[i]) - 2*trans(s[i - 1]);
} else {
result += trans(s[i]);
}
}
return result;
}
};
Result
说点别的
吐槽一下,题干没有给出罗马数字对应的转换,一般人(我)大概也就知道1-10,很尴尬。然后这题的要点是找规律……?