# 【LeetCode】 13. Roman to Integer ## Description > Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. ``` Symbol Value I 1 V 5 X 10 L 50 C 100 D 500 M 1000 ``` > For example, two is written as II in Roman numeral, just two one's added together. Twelve is written as, XII, which is simply X + II. The number twenty seven is written as XXVII, which is XX + V + II. > Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: > - I can be placed before V (5) and X (10) to make 4 and 9. > - X can be placed before L (50) and C (100) to make 40 and 90. > - C can be placed before D (500) and M (1000) to make 400 and 900. > Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999. > 羅馬數字用七個符號來表示數字:I、V、X、L、C、D和M。 > 分別對應到的數字請參照上方。 > 舉例來說,"二"在羅馬數字中我們會寫成"II",代表兩個一相加;"十二"則是寫成"XII",也就是X + II;"二十七"則是寫成"XXVII",代表XX + V + II。 > 羅馬數字通常從大到小會左到右的順序撰寫,然而數字"四"卻不是寫成"IIII",取而代之的是"IV",一在五之前代表的是五要減掉一。同樣的,數字九會寫成IX。我們直接列出六種所有可能的減法情形給你: > - I可以放在V(5)和X(10)前面來完成4和9。 > - X可以放在L(50)和C(100)前面來完成40和90。 > - C可以放在D(500)和M(1000)前面來完成400和900。 > 給予一個羅馬數字,請將它轉換為一般整數。數字大小只會在1到3999之間。 ## Example: ``` Example 1: Input: "III" Output: 3 Example 2: Input: "IV" Output: 4 Example 3: Input: "IX" Output: 9 Example 4: Input: "LVIII" Output: 58 Explanation: L = 50, V= 5, III = 3. Example 5: Input: "MCMXCIV" Output: 1994 Explanation: M = 1000, CM = 900, XC = 90 and IV = 4. ``` ## Solution * 按照規則硬爆開來即可。 * 如果發現是做減法運算,記得要連多加的部分一併扣回。 * 可以寫成switch case,看個人習慣。 ### Code ```C++=1 class Solution { public: int romanToInt(string s) { int count=0; bool I=false,X=false,C=false; for(int i=0;i<s.size();i++) { if(s[i]=='M') { count+=1000; if(C) { C=false; count-=200; } } else if(s[i]=='D') { count+=500; if(C) { C=false; count-=200; } } else if(s[i]=='C') { count+=100; C=true; if(X) { X=false; count-=20; } } else if(s[i]=='L') { count+=50; if(X) { X=false; count-=20; } } else if(s[i]=='X') { count+=10; X=true; if(I) { I=false; count-=2; } } else if(s[i]=='V') { count+=5; if(I) { I=false; count-=2; } } else if(s[i]=='I') { count+=1; I=true; } } return count; } }; ``` ###### tags: `LeetCode` `C++`