Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
解题思路:
类似上题,方法多多,本题直接给出上题中字典匹配的代码:
JAVA实现:
static public int romanToInt(String s) { int num=0; String Roman[][] = { {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"}, {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"}, {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"}, {"", "M", "MM", "MMM"} }; StringBuilder sb=new StringBuilder(s); for(int i=Roman.length-1;i>=0;i--){ //由于罗马字母无法表示0,因此,可以认为j>=1 for(int j=Roman[i].length-1;j>=1;j--){ if(sb.length()>=Roman[i][j].length()&&sb.substring(0,Roman[i][j].length()).equals(Roman[i][j])){ num+=j*Math.pow(10, i); sb.delete(0,Roman[i][j].length()); break; } } } return num; }
C++:
1 class Solution { 2 public: 3 int romanToInt(string s) { 4 int num = 0; 5 vector<vector<string>> Roman = { 6 { "", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX" }, 7 { "", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC" }, 8 { "", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM" }, 9 { "", "M", "MM", "MMM" } 10 }; 11 string sb = s; 12 for (int i = Roman.size() - 1; i >= 0; i--) { 13 //由于罗马字母无法表示0,因此,可以认为j>=1 14 for (int j = Roman[i].size() - 1; j >= 1; j--) { 15 if (sb.length() >= Roman[i][j].length() && sb.substr(0, Roman[i][j].length())==(Roman[i][j])) { 16 num += j*pow(10, i); 17 sb.erase(0,Roman[i][j].length()); 18 break; 19 } 20 } 21 } 22 return num; 23 } 24 };