标签:
原题链接:https://oj.leetcode.com/problems/roman-to-integer/
比较简单的题,代码应该还可以稍微优化,更generic一些。
class Solution { public: int romanToInt(string s) { if (s.size() == 0) return 0; int num = 0; for (int i = s.size() - 1; i >= 0; --i) { switch (s[i]) { case 'I': ++num; if (i + 1 < s.size() && (s[i + 1] == 'X' || s[i + 1] == 'V')) { num -= 2; } break; case 'V': num += 5; break; case 'X': num += 10; if (i + 1 < s.size() && (s[i + 1] == 'L' || s[i + 1] == 'C')) { num -= 20; } break; case 'L': num += 50; break; case 'C': num += 100; if (i + 1 < s.size() && (s[i + 1] == 'D' || s[i + 1] == 'M')) { num -= 200; } break; case 'D': num += 500; break; case 'M': num += 1000; break; } } return num; } };
[Leetcode] 13 - Roman to Integer
标签:
原文地址:http://blog.csdn.net/algorithmengine/article/details/42642961