Advertisement
fueanta

Roman to Integer.

Jun 1st, 2017
194
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.72 KB | None | 0 0
  1. #include <iostream>
  2. #include <unordered_map>
  3. #include <string>
  4.  
  5. using namespace std;
  6.  
  7. class Solution {
  8. public:
  9.     int romanToInt(string s) {
  10.         unordered_map<char, int> romanVal = {
  11.             {'I', 1},
  12.             {'V', 5},
  13.             {'X', 10},
  14.             {'L', 50},
  15.             {'C', 100},
  16.             {'D', 500},
  17.             {'M', 1000}
  18.         };
  19.         int sum = romanVal[s.back()];
  20.         for (int i = s.size() - 2; i >= 0; --i)
  21.         {
  22.             if (romanVal[s[i]] < romanVal[s[i + 1]])
  23.             {
  24.                 sum -= romanVal[s[i]];
  25.             }
  26.             else
  27.             {
  28.                 sum += romanVal[s[i]];
  29.             }
  30.         }
  31.         return sum;
  32.     }
  33. };
  34.  
  35. int main(void)
  36. {
  37.     Solution s;
  38.     string romanNum;
  39.     cout << "Roman Number: ";
  40.     getline(cin, romanNum);
  41.     cout << "Integer Number: " << s.romanToInt(romanNum) << "\n\n";
  42.     return 0;
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement