LeetCode 13 Roman to Integer

Problem:

Given a roman numeral, convert it to an integer.

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

Summary:

将罗马数字转换为十进制阿拉伯数字。

Analysis:

罗马数字和阿拉伯数字的转换关系如下图:

罗马数字的基本字符:

罗马数字 I V X L C D M
阿拉伯数字 1 5 10 50 100 500 1000

普通罗马数字的计算规则为:若小的数字在大的数字左边,则用大的数字减去小的数字;若小的数字在大的数字右边,则用大的数字加上小的数字。

在代码中,首先用map记录基本字符所对应的阿拉伯数字,再遍历字符串,按照计算规则计算即可。

 1 class Solution {
 2 public:
 3     int romanToInt(string s) {
 4         map<char, int> m;
 5         m['I'] = 1;
 6         m['V'] = 5;
 7         m['X'] = 10;
 8         m['L'] = 50;
 9         m['C'] = 100;
10         m['D'] = 500;
11         m['M'] = 1000;
12         
13         int len = s.size();
14         int res = m[s[len - 1]];
15         
16         for (int i = len - 2; i >= 0; i--) {
17             if(m[s[i + 1]] > m[s[i]]) {
18                 res -= m[s[i]];
19             }
20             else {
21                 res += m[s[i]];
22             }
23         }
24         
25         return res;
26     }
27 };
原文地址:https://www.cnblogs.com/VickyWang/p/6012837.html