标签:
题目描述:
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
这道题很简单,我就直接贴答案了。
solution1:
int romanToInt(string s) { int res = 0; char ch; int n = s.size(); s += "#"; for (int i = 0;i < n;++i) { ch = s[i]; switch(ch){ case ‘I‘: if(s[i+1] == ‘V‘ || s[i+1] == ‘X‘) res -= 1; else res += 1; break; case ‘V‘: res += 5; break; case ‘X‘: if(s[i+1] == ‘L‘ || s[i+1] == ‘C‘) res -= 10; else res += 10; break; case ‘L‘: res += 50; break; case ‘C‘: if(s[i+1] == ‘D‘ || s[i+1] == ‘M‘) res -= 100; else res += 100; break; case ‘D‘: res += 500; break; case ‘M‘: res += 1000; break; default: break; } } return res; }
上面是我自己写的,下面用了map,代码看起来简洁些。
solution2:
int romanToInt(string s) { map<char,int> m; m[‘M‘] = 1000; m[‘D‘] = 500; m[‘C‘] = 100; m[‘L‘] = 50; m[‘X‘] = 10; m[‘V‘] = 5; m[‘I‘] = 1; int result = 0; int i; for(i = 0;i < s.size()-1;++i) { if(m[s[i]] < m[s[i+1]]) result -= m[s[i]]; else result += m[s[i]]; } result += m[s[i]]; return result; }
标签:
原文地址:http://www.cnblogs.com/gattaca/p/4278057.html