【題目】
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
【分析】
這個和上篇博文中把數字轉換爲羅馬數字正好相反,邏輯過程有點兒複雜。
其實解法來源於對羅馬數字(字符串)的觀察,在解析這個字符串的時候,我們可以分成兩種情況:
1)如果former大於等於current,那麼結果可以直接加上current的數值;
2)如果former較小,那麼我們需要用current - former*2. 這裏爲什麼需要減去2倍的former,因爲former在前面一定是先加上過一次,例如:XIV, 過程是10+1+5-2*1=14,看到了吧,1在前面一定是已經加上了一次了。
【代碼】
class Solution {
public:
int romanToInt(string s) {
int res = 0;
int len = s.length();
res += convert(s[0]);
for(int i = 1; i < len; i++)
{
int current = convert(s[i]);
int former = convert(s[i - 1]);
if(former >= current) // the former one is larger than or equalling to the later one
{
res += current;
}
else
{
res += current - 2*former;
}
}
return res;
}
int convert(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;
}
};