LeetCode 13. Roman to Integer
阿新 • • 發佈:2017-06-24
cnblogs 如果 mes std line logs urn onclick +=
https://leetcode.com/problems/roman-to-integer/#/description
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。
- 羅馬數字_百度百科
- http://baike.baidu.com/link?url=JBuRWsGjAmYIlIhaPN_ywmIJBMrTWT6iKb2-WhqyTA6RqitOQuqnvQ2PHVfelAf00iGWWtgTzUjB3W4YMR0XWLfadA6YVi_s2J1aUgb-n1eBewvqGmyRpdH3VsVVs4q3
1 #include <iostream> 2 #include <string> 3 using namespace std; 4 5 class Solution { 6 public: 7 inline int map(const char inCh) 8 { 9 switch (inCh) 10 { 11 case ‘I‘: return 1; 12 case ‘V‘: return 5; 13 caseView Code‘X‘: return 10; 14 case ‘L‘: return 50; 15 case ‘C‘: return 100; 16 case ‘D‘: return 500; 17 case ‘M‘: return 1000; 18 default: return 0; 19 } 20 21 } 22 23 int romanToInt(string s) 24 { 25 intresult = 0; 26 27 for (size_t i = 0; i < s.size(); i ++) { 28 if ((i > 0) && (map(s[i]) > map(s[i - 1]))) { 29 result += map(s[i]) - 2 * map(s[i - 1]); 30 } else { 31 result += map(s[i]); 32 } 33 } 34 35 return result; 36 } 37 }; 38 39 int main () 40 { 41 Solution testSolution; 42 string sTest[] = {"XXI", "XXIX"}; 43 44 for (int i = 0; i < 2; i ++) 45 cout << testSolution.romanToInt(sTest[i]) << endl; 46 47 return 0; 48 }
LeetCode 13. Roman to Integer