力扣 题目13- 罗马数字转整数
题目
题解
方法1:用Map形成罗马字母与整数的映射关系 然后从右往左遍历 如果下一个小于等于自身就为加 下一个 大于自身就为减
方法2:将罗马数字拆分成整数位数的形式 然后再用上一题的表格的思想 返回下标再乘以位数(10的次方)即可
代码
方法1:
#include<iostream> #include<map> #include<string> using namespace std; map<string, int>m = { pair<string, int>("I", 1), pair<string, int>("V", 5), pair<string, int>("X", 10), pair<string, int>("L", 50), pair<string, int>("C", 100), pair<string, int>("D", 500), pair<string, int>("M", 1000), }; int second(char s) { string ss = ""; ss = ss + s; map<string, int>::iterator pos = m.find(ss); return (*pos).second; } class Solution { public: int romanToInt(string s) { int ans = 0; for (int i = 0; i < s.size(); i++) { int value = second(s[i]); if (i < s.size() - 1 && value < second(s[i + 1])) { ans -= value; } else { ans += value; } } return ans; } }; int main() { Solution sol; string Rome = "MCMXCIV"; int integer=sol.romanToInt(Rome); cout << integer << endl; }
方法2:
#include<iostream> #include<string> #include<vector> using namespace std; vector<string> thousands2 = { "", "M", "MM", "MMM" }; vector<string> hundreds2 = { "", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM" }; vector<string> tens2 = { "", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC" }; vector<string> ones2 = { "", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX" }; const string thousands="M"; const string hundreds = "CDM"; const string tens = "XLC"; const string ones = "IVX"; int ergodic(string &Number,vector<string> &Rome) { int subscript=0; for (int i = 0; i < Rome.size(); i++) { if (Number == Rome[i]) { subscript = i; break; } } return subscript; } class Solution { public: int romanToInt(string s) { bool digit[4] = { 1,1,1,1 }; int integer = 0; string thousands3=""; string hundreds3 = ""; string tens3 = ""; string ones3 = ""; for (int i = 0; i < s.size();i++) { if (thousands.find(s[i])!=-1&& digit[0]) { thousands3 = thousands3 + s[i]; } else if (hundreds.find(s[i]) != -1 && digit[1]) { hundreds3 = hundreds3 + s[i]; digit[0] = 0; } else if (tens.find(s[i]) != -1 && digit[2]) { tens3 = tens3 + s[i]; digit[1] = 0; } else if (ones.find(s[i]) != -1 && digit[3]) { ones3 = ones3 + s[i]; digit[2] = 0; } } integer = ergodic(thousands3, thousands2)*1000 + ergodic(hundreds3, hundreds2)*100 + ergodic(tens3, tens2)*10 + ergodic(ones3, ones2); return integer; } }; int main() { Solution sol; string Rome = "IV"; int integer=sol.romanToInt(Rome); cout << integer << endl; }