题目:
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
提示:
此题只要熟悉罗马数字的书写语法,做起来就不会太难,关于罗马数字的介绍可以参考这里。
代码:
从左往右转换的方法:
class Solution { public: int value(char c) { if (c == 'I') return 1; if (c == 'X') return 10; if (c == 'C') return 100; if (c == 'M') return 1000; if (c == 'V') return 5; if (c == 'L') return 50; if (c == 'D') return 500; } int romanToInt(string s) { if (s.size() == 0) return 0; if (s.size() == 1) return value(s[0]); int current, next, sum = 0, i = 0; for (; i < s.size() - 1; ++i) { current = value(s[i]); next = value(s[i+1]); sum += current < next ? -current : current; } sum += value(s[i]); return sum; } };
从右往左转换的方法:
class Solution { public: int romanToInt(string s) { int res = 0; for (int i = s.length() - 1; i >= 0; i--) { char c = s[i]; switch (c) { case 'I': res += (res >= 5 ? -1 : 1); break; case 'V': res += 5; break; case 'X': res += 10 * (res >= 50 ? -1 : 1); break; case 'L': res += 50; break; case 'C': res += 100 * (res >= 500 ? -1 : 1); break; case 'D': res += 500; break; case 'M': res += 1000; break; } } return res; } };