题目描述:(链接)
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
解题思路:
1 class Solution { 2 public: 3 int romanToInt(string s) { 4 int len = s.size(); 5 if (len < 1) return 0; 6 7 int result = 0; 8 int sub = getRomanValue(s[0]); 9 int lastV = sub; 10 for (int i = 1; i < len; ++i) { 11 char curC = s[i]; 12 int curV = getRomanValue(curC); 13 if (curV == lastV) { 14 sub += curV; 15 } else if (curV < lastV) { 16 result += sub; 17 sub = curV; 18 } else { 19 sub = curV - lastV; 20 } 21 lastV = curV; 22 } 23 24 result += sub; 25 return result; 26 } 27 private: 28 int getRomanValue(char c) { 29 switch(c) { 30 case ‘I‘: return 1; 31 case ‘V‘: return 5; 32 case ‘X‘: return 10; 33 case ‘L‘: return 50; 34 case ‘C‘: return 100; 35 case ‘D‘: return 500; 36 case ‘M‘: return 1000; 37 default: return 0; 38 } 39 } 40 };
原文:http://www.cnblogs.com/skycore/p/4959856.html