[LeetCode 题解]: Roman to Interger

前言

 

【LeetCode 题解】系列传送门:  http://www.cnblogs.com/double-win/category/573499.html

 

1.题目描述

Given a roman numeral, convert it to an integer.

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

2. 思路

找到规则即可

罗马数字的表示:

I~1 V~5 X~10 L~50 C~100 D~500 M~1000

规则:

基本数字Ⅰ、X 、C 中的任何一个,自身连用构成数目,或者放在大数的右边连用构成数目,都不能超过三个;放在大数的左边只能用一个。

不能把基本数字V 、L 、D 中的任何一个作为小数放在大数的左边采用相减的方法构成数目;放在大数的右边采用相加的方式构成数目,只能使用一个。

默认所有输入均为正确表示的罗马数字.

如果在输入中有不符合规则的数字,就需要加特殊的判断。

有几条须注意掌握:

  1. V 和X 左边的小数字只能用Ⅰ。
  2. L 和C 左边的小数字只能用X。
  3. D 和M 左边的小数字只能用C。       --摘自百度百科http://baike.baidu.com/view/42061.htm?fr=aladdin

在此就不赘述了

3. 解法

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

4. 相关题目

相对应的一道题:Roman to Interger : http://www.cnblogs.com/double-win/p/3760002.html

作者:Double_Win

出处:   http://www.cnblogs.com/double-win/p/3761803.html

声明: 由于本人水平有限,文章在表述和代码方面如有不妥之处,欢迎批评指正~

posted @ 2014-05-29 20:40  Double_win  阅读(295)  评论(0编辑  收藏  举报