首页 > 代码库 > LeetCode 13. Roman to Integer
LeetCode 13. Roman to Integer
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
罗马数字:可以查看维基百科的定义
.
最大为MMMCMXCIX,我们需要注意的是9的写法是IX,4的写法是IV
这样我们遍历整个字符串后就可以得到结果,也可以将求值重新封装
成一个新的函数,因为好多部分都是重复的,下面是代码
class Solution {public: int romanToInt(string s) { int sum = 0; int cnt = 0; int i = 0; if (i + cnt<s.size() && s[i] == ‘M‘) { ++cnt; for (;s[i + cnt] == ‘M‘;++cnt); sum += cnt * 1000; i += cnt; cnt = 0; } if (i + cnt < s.size() && s[i] == ‘D‘) { ++cnt; for (;s[i + cnt] == ‘C‘;++cnt); sum += (4 + cnt) * 100; i += cnt; cnt = 0; } if (i + cnt < s.size()&&s[i] == ‘C‘) { ++cnt; for (;s[i + cnt] == ‘C‘;++cnt); if (1 == cnt) { if (s[i + cnt] != ‘M‘&&s[i + cnt] != ‘D‘) { sum += 100; i += cnt; cnt = 0; } if (s[i + cnt] == ‘M‘) { ++cnt; sum += 900; i += cnt; cnt = 0; } if (s[i + cnt] == ‘D‘) { ++cnt; sum += 400; i += cnt; cnt = 0; } } if (2 == cnt) { sum += 200; i += cnt; cnt = 0; } if (3 == cnt) { sum += 300; i += cnt; cnt = 0; } } if (i + cnt < s.size() && s[i] == ‘L‘) { ++cnt; for (;s[i + cnt] == ‘X‘;++cnt); sum += (4 + cnt) * 10; i += cnt; cnt = 0; } if (i + cnt < s.size() && s[i] == ‘X‘) { ++cnt; for (;s[i + cnt] == ‘X‘;++cnt); if (1 == cnt) { if (s[i + cnt] != ‘L‘&&s[i + cnt] != ‘C‘) { sum += 10; i += cnt; cnt = 0; } if (s[i + cnt] == ‘C‘) { ++cnt; sum += 90; i += cnt; cnt = 0; } if (s[i + cnt] == ‘L‘) { ++cnt; sum += 40; i += cnt; cnt = 0; } } if (2 == cnt) { sum += 20; i += cnt; cnt = 0; } if (3 == cnt) { sum += 30; i += cnt; cnt = 0; } } if (i + cnt < s.size() && s[i] == ‘V‘) { ++cnt; for (;s[i + cnt] == ‘I‘;++cnt); sum += (4 + cnt) * 1; i += cnt; cnt = 0; } if (i + cnt < s.size() && s[i] == ‘I‘) { ++cnt; for (;s[i + cnt] == ‘I‘;++cnt); if (1 == cnt) { if (s[i + cnt] != ‘V‘&&s[i + cnt] != ‘X‘) { sum += 1; i += cnt; cnt = 0; } if (s[i + cnt] == ‘X‘) { ++cnt; sum += 9; i += cnt; cnt = 0; } if (s[i + cnt] == ‘V‘) { ++cnt; sum += 4; i += cnt; cnt = 0; } } if (2 == cnt) { sum += 2; i += cnt; cnt = 0; } if (3 == cnt) { sum += 3; i += cnt; cnt = 0; } } return sum; }};
LeetCode 13. Roman to Integer
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。