題目:
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
解題思路:我們首先來明確一下羅馬數字與阿拉伯數字的換算規則:如果當前數字比前一個大,說明這一段的值應該是當前這個值減去上一個值,比如IV = 5 – 1;否
則,將當前值加入到結果中,然後開始下一段記錄,比如VI = 5 + 1, II=1+1。而羅馬數字與阿拉伯數字對應變換是:I對應1,V對應5,X對應10,L對應50,C對應100,D對應500,M對應1000。因此,只需要從前往後讀出字符,如果當前數字小於等於前一字符,則加上當前字符對應的數字;而當前數字更大時,減去前一個字符(要減去兩倍,因為在前面掃描時已經加上過一次了,實際上不應該加,因此要多減一次)。
代碼:
class Solution {
public:
inline int map(const 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;
default:return 0;
}
}
int romanToInt(string s) {
const size_t n=s.size();
int result=0;
for(int i=0;i0&&(map(s[i])>map(s[i-1]))){
result=result+map(s[i])-2*map(s[i-1]);
}else{
result=result+map(s[i]);
}
}
return result;
}
};