首页 > 代码库 > Roman to Integer
Roman to Integer
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
1 class Solution { 2 public: 3 int romanToInt(string s) { 4 if (s.empty()) return 0; 5 6 int result = 0; 7 int n = s.size(); 8 unordered_map<char, int> roman; 9 roman[‘I‘] = 1;10 roman[‘V‘] = 5;11 roman[‘X‘] = 10;12 roman[‘L‘] = 50;13 roman[‘C‘] = 100;14 roman[‘D‘] = 500;15 roman[‘M‘] = 1000;16 17 for (int i = 0; i < n; i++) {18 if (i < n - 1) {19 if (s[i] == ‘I‘ && s[i + 1] == ‘V‘) {result += 4; i++;}20 else if (s[i] == ‘I‘ && s[i + 1] == ‘X‘) {result += 9; i++;}21 else if (s[i] == ‘X‘ && s[i + 1] == ‘L‘) {result += 40; i++;}22 else if (s[i] == ‘X‘ && s[i + 1] == ‘C‘) {result += 90; i++;}23 else if (s[i] == ‘C‘ && s[i + 1] == ‘D‘) {result += 400; i++;}24 else if (s[i] == ‘C‘ && s[i + 1] == ‘M‘) {result += 900; i++;}25 else result += roman[s[i]];26 }27 else {28 result += roman[s[i]];29 }30 }31 return result;32 }33 };
Roman to Integer
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。