首页 > 代码库 > Roman to Integer

Roman to Integer

Given a roman numeral, convert it to an integer.

Input is guaranteed to be within the range from 1 to 3999.

思路:从后往前遍历,如果某个数比其后一个数小,则减去该数;否则,加上该数。因为只存在Ⅳ(4)、XL(40)、CD(400)等一类的逆序情况,而这些数的共同点是前一个数的重复次数均为1。

 1 class Solution { 2 public: 3     int romanToInt( string s ) { 4         if( s.empty() ) { return 0; } 5         unordered_map<char,int> romanMap; 6         romanMap[I] = 1; 7         romanMap[V] = 5; 8         romanMap[X] = 10; 9         romanMap[L] = 50;10         romanMap[C] = 100;11         romanMap[D] = 500;12         romanMap[M] = 1000;13         int ret = romanMap[s.back()];14         for( int i = (int)s.size()-2; i >= 0 ; --i ) {15             if( romanMap[s[i]] < romanMap[s[i+1]] ) {16                 ret -= romanMap[s[i]];17             } else {18                 ret += romanMap[s[i]];19             }20         }21         return ret;22     }23 };

 

Roman to Integer