題目:
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
題意:
給定一個羅馬數字,轉換爲整數。
思路:
首先,我們明確,羅馬數字各個字符代表什麼:
I:1
V:5
X:10
L:50
C:100
D:500
M:1000。
並且比如 IV = 4,IX = 9; XL =40, XC =90, CD = 400, CM = 900。並且只有這6個數字是特殊的,是讓後面的數字減去前面的數字。
所以我們不妨掃描的時候將這個羅馬數字代表的數字加入結果中。比如掃描IX,先將I代表的1加入,再將X代表的10加入,當到達X的時候,我們判斷它前面是不是I,如果是的話說明應該需要用10減去1,因爲我們剛纔是將1+10了,這個1先要減去一次得到10,還需要再減去一次得到9,也就是掃描到X時發現前面一個字符是I的時候,需要減去兩次I代表的值。因爲本來就多加了一次,而實際本來需要減去一次,所以當前就要減去兩次。
以上。
代碼如下:
class Solution {
public:
int romanToInt(string s){
int index = 1;
int count = 0;
s = "0" + s;
int size = s.length();
while (index < size) {
switch (s[index]) {
case 'I': count++; break;
case 'V': {
count = (s[index - 1] == 'I')?count -= 2:count;
count += 5; break;
}
case 'X': {
count = (s[index - 1] == 'I')?count -= 2:count;
count += 10; break;
}
case 'L': {
count = (s[index - 1] == 'X')?count -= 20:count;
count += 50; break;
}
case 'C': {
count = (s[index - 1] == 'X')?count -= 20:count;
count += 100; break;
}
case 'D': {
count = (s[index - 1] == 'C')?count -= 200:count;
count += 500; break;
}
case 'M': {
count = (s[index - 1] == 'C')?count -= 200:count;
count += 1000; break;
}
}
index++;
}
return count;
}
};