1 class Solution { 2 public: 3 int romanToInt(string s) { 4 unordered_map<char,int> m; 5 m['I'] = 1; 6 m['V'] = 5; 7 m['X'] = 10; 8 m['L'] = 50; 9 m['C'] = 100; 10 m['D'] = 500; 11 m['M'] = 1000; 12 13 int res = 0; 14 int pre = 0; 15 int len = s.length(); 16 for(int i=len-1;i>=0;i--){ 17 int a = m[s[i]]; 18 if(a >= pre){ 19 pre = a; 20 res += a; 21 }else{ 22 pre = a; 23 res -= a; 24 } 25 } 26 return res; 27 } 28 }; 29 class Solution { 30 public: 31 string intToRoman(int num) { 32 char* c[4][10]={ 33 {"","I","II","III","IV","V","VI","VII","VIII","IX"}, 34 {"","X","XX","XXX","XL","L","LX","LXX","LXXX","XC"}, 35 {"","C","CC","CCC","CD","D","DC","DCC","DCCC","CM"}, 36 {"","M","MM","MMM"} 37 }; 38 string roman; 39 roman.append(c[3][num / 1000 % 10]); 40 roman.append(c[2][num / 100 % 10]); 41 roman.append(c[1][num / 10 % 10]); 42 roman.append(c[0][num % 10]); 43 44 return roman; 45 } 46 };