fork(1) download
  1. #include <iostream>
  2. #include <string>
  3. #include <map>
  4. #include <vector>
  5.  
  6. const std::map<char, int> letter_map{
  7. {'I', 1},
  8. {'V', 5},
  9. {'X', 10},
  10. {'L', 50},
  11. {'C', 100},
  12. {'D', 500},
  13. {'M', 1000}
  14. };
  15.  
  16. int RomanToInt(const std::string & s) {
  17. int len = s.length();
  18. std::vector<int> values(len);
  19. for (int i = 0; i < len; ++i) {
  20. values[i] = letter_map.at(s[i]);
  21. }
  22. int res = values[len - 1];
  23. for (int i = 0; i + 1 < len; ++i) {
  24. if (values[i] < values[i + 1]) {
  25. res -= values[i];
  26. } else {
  27. res += values[i];
  28. }
  29. }
  30. return res;
  31. }
  32.  
  33. int main() {
  34. // your code goes here
  35. std::string s;
  36. std::cin >> s;
  37. std::cout << RomanToInt(s) << std::endl;
  38. return 0;
  39. }
Success #stdin #stdout 0s 3476KB
stdin
MMMCMLXXXIX
stdout
3989