题目
描述
把用字符串形式表达的罗马数字转换成十进制整数形式,整数范围为 1 到 3999。
代码
class Solution { public: int romanToInt(string s){ map<char, int> roman; roman['I'] = 1; roman['V'] = 5; roman['X'] = 10; roman['L'] = 50; roman['C'] = 100; roman['D'] = 500; roman['M'] = 1000; int sum = 0; int len = s.size(); for(int i=0; i<len;){ int c1 = s[i]; if(i==len-1){ // last char sum += roman[s[i]]; break; } else{ int n=i+1; while(s[n]==s[i] && n<len) n++; n = n - (i+1)+1; if(n>1){ sum += n*roman[s[i]]; i += n; } else{ if(roman[s[i]] < roman[s[i+1]]){ sum += roman[s[i+1]] - roman[s[i]]; i+=2; } else{ sum += roman[s[i]]; i++; } } } } return sum; } };