Roman to Integer leetcode
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
Subscribe to see which companies asked this question
Ⅰ(1)Ⅴ(5)Ⅹ(10)L(50)C(100)D(500)M(1000)
规则:位于大数的后面时就作为加数;位于大数的前面就作为减数
如:Ⅲ=3,Ⅳ=4,Ⅵ=6,ⅩⅨ=19,ⅩⅩ=20,ⅩLⅤ=45,MCMⅩⅩC=1980
从最低位开始,如果前面的数比它大,则让前面的数值加后面的数值,如果比它小,则让当前数值减去前面的数值
int romanToInt(string s) { if (s.length() == 0) return 0; int len = s.length(); unordered_map<char, int> map; map.insert(make_pair('I', 1)); map.insert(make_pair('V', 5)); map.insert(make_pair('X', 10)); map.insert(make_pair('L', 50)); map.insert(make_pair('C', 100)); map.insert(make_pair('D', 500)); map.insert(make_pair('M', 1000)); int result = map.at(s.at(len - 1)); int pivot = result; for (int i = len - 2; i >= 0; i--) { int curr = map.at(s.at(i)); if (curr >= pivot) { result += curr; } else { result -= curr; } pivot = curr; } return result; }