Advertisement
vmontes

roman-to-integer

Sep 8th, 2020
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.26 KB | None | 0 0
  1. #include <list>
  2.  
  3. class Solution
  4. {
  5. public:
  6.  
  7. list<int> t;
  8.  
  9. int sumchar(char c)
  10. {
  11. switch (c)
  12. {
  13. case 'I':
  14. return 1;
  15. case 'V':
  16. return 5;
  17. case 'X':
  18. return 10;
  19. case 'L':
  20. return 50;
  21. case 'C':
  22. return 100;
  23. case 'D':
  24. return 500;
  25. case 'M':
  26. return 1000;
  27. }
  28. return 0;
  29. };
  30.  
  31. int romanToInt(string s)
  32. {
  33. for (int i = 0; i < s.size(); i++)
  34. {
  35. int r = sumchar(s[i]);
  36. if (t.empty())
  37. t.push_back(r);
  38. else
  39. {
  40. if (t.back() < r)
  41. {
  42. int sum = 0;
  43. while ((!t.empty()) && (t.back() < r))
  44. {
  45. sum += t.back();
  46. t.pop_back();
  47. }
  48. t.push_back(r - sum);
  49. }
  50. else
  51. {
  52. t.push_back(r);
  53. }
  54. }
  55. }
  56.  
  57. return std::accumulate(t.begin(), t.end(), 0);
  58. }
  59. };
  60.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement