class Solution { public: int romanToInt(string s) { if (s.length() < 1) return 0; map<char,int> m; m['I'] = 1; m['V'] = 5; m['X'] = 10; m['L'] = 50; m['C'] = 100; m['D'] = 500; m['M'] = 1000; int i = s.length() - 1; int sum = m[s[i--]]; while (i >= 0) { if (m[s[i + 1]] > m[s[i]]) sum -= m[s[i]]; else sum += m[s[i]]; --i; } return sum; } };
class Solution { public: string intToRoman(int num) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. string symbol[]={"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"}; int value[]={1000,900,500,400,100,90,50,40,10,9,5,4,1}; string res = ""; int i = 0; while (num > 0) { if (num >= value[i]) { res += symbol[i]; num -= value[i]; } else ++i; } return res; } };