leetcode

Leetcode submissions
git clone git://git.laack.co/leetcode.git
Log | Files | Refs | README

roman-to-integer.cpp (799B)


      1 #include <string>
      2 #include <iostream>
      3 #include <vector>
      4 #include <map>
      5 
      6 
      7 //Leet Ratings
      8 //       Speed  Memory
      9 //Total  41ms   8.2MB    
     10 //Beats  6.1%   40.21%
     11 //
     12 
     13 
     14 
     15 using namespace std;
     16 
     17 
     18 int romanToInt(string s) {
     19     
     20     map <char, int> vals = {};
     21     vals.insert({'I', 1});
     22     vals.insert({'V', 5});
     23     vals.insert({'X', 10});
     24     vals.insert({'L', 50});
     25     vals.insert({'C', 100});
     26     vals.insert({'D', 500});
     27     vals.insert({'M', 1000});
     28 
     29     int return_val;
     30     int lv = 1000;
     31     int cv;
     32     for(int i = 0 ; i < s.length() ; ++i ){
     33         cv = vals.find(s[i])->second;
     34         if(lv < cv){
     35             return_val -= lv * 2;
     36         }
     37         return_val += cv;
     38         lv = cv;
     39     }
     40     return (return_val);
     41 }
     42 
     43 
     44 int main(){
     45     cout << romanToInt("MCMXCIV") << endl;
     46     return 0;
     47 }
     48