leetcode

Solution to some Leetcode problems written in C++
git clone git://git.dimitrijedobrota.com/leetcode.git
Log | Files | Refs | README | LICENSE

0013.cpp (690B)


      1 class Solution {
      2   public:
      3     int value(char c) {
      4         switch (c) {
      5         case 'I': return 1;
      6         case 'V': return 5;
      7         case 'X': return 10;
      8         case 'L': return 50;
      9         case 'C': return 100;
     10         case 'D': return 500;
     11         case 'M': return 1000;
     12         default: return -10000;
     13         }
     14     }
     15 
     16     int romanToInt(string s) {
     17         int size = s.size();
     18         int res = 0;
     19         for (int i = 0; i < size - 1; i++) {
     20             int a = value(s[i]);
     21             int b = value(s[i + 1]);
     22             if (a >= b)
     23                 res += a;
     24             else
     25                 res -= a;
     26         }
     27         res += value(s[size - 1]);
     28 
     29         return res;
     30     }
     31 };