[題目]
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
[中文翻譯]
給定一個羅馬數字,將其轉換爲整數。
輸入保證在1到3999的範圍內。
[解題思路]
羅馬數字轉換爲整數的規律較爲簡單。
羅馬數字 | 整數 |
---|---|
‘I’ | 1 |
‘V’ | 5 |
‘X’ | 10 |
‘L’ | 50 |
‘C’ | 100 |
‘D’ | 500 |
‘M’ | 1000 |
正常情況下,羅馬數字的排列,是從大到小的,如’VII’代表5+1+1=7,但有一些特殊的情況,如’IV’表示5-1=4,’CD’表示500-100=400,這些特殊情況,都是小的字符排在了大的字符前面,這種情況下,在計算的時候需要減去小的字符。
很慶幸,這些小字符排在大字符前面的情況,只會以兩個字符的形式出現,即不會用’IIV’表示5-1-1=3,或者用’CCD’表示500-100-100=300。
因此,在程序裏,只要從前往後遍歷每個羅馬字符,判斷一下該字符A是否與之後的字符B形成逆序對,如果是,則處理這兩個字符,result=result+B-A;如果不是則只處理該字符,result=result+A。
[C++代碼]
class Solution {
public:
int romanToInt(string s) {
int roman[256];
int res = 0;
roman['I'] = 1;
roman['V'] = 5;
roman['X'] = 10;
roman['L'] = 50;
roman['C'] = 100;
roman['D'] = 500;
roman['M'] = 1000;
for (int i = 0; i < s.size(); ) {
if (i + 1 < s.size() && roman[s.at(i)] < roman[s.at(i + 1)]) {
res = res + roman[s.at(i + 1)] - roman[s.at(i)];
i += 2;
}
else {
res = res + roman[s.at(i)];
i++;
}
}
return res;
}
};