码迷,mamicode.com
首页 > 其他好文 > 详细

【LeetCode】013. Roman to Integer

时间:2018-03-25 17:00:41      阅读:237      评论:0      收藏:0      [点我收藏+]

标签:ble   com   数字   post   相加   rip   tco   blank   www   


Given a roman numeral, convert it to an integer.

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

 

题解:

  只要知道罗马数字的规律即可

  

基本字符
I
V
X
L
C
D
M
相应的阿拉伯数字表示为
1
5
10
50
100
500
1000
 
1、相同的数字连写,所表示的数等于这些数字相加得到的数,如:Ⅲ = 3;
2、小的数字在大的数字的右边,所表示的数等于这些数字相加得到的数, 如:Ⅷ = 8;Ⅻ = 12;
3、小的数字,(限于Ⅰ、X 和C)在大的数字的左边,所表示的数等于大数减小数得到的数,如:Ⅳ= 4;Ⅸ= 9;
4、正常使用时,连写的数字重复不得超过三次。(表盘上的四点钟“IIII”例外)
5、在一个数的上面画一条横线,表示这个数扩大1000倍。
 
有几条须注意掌握:
1、基本数字Ⅰ、X 、C 中的任何一个,自身连用构成数目,或者放在大数的右边连用构成数目,都不能超过三个;放在大数的左边只能用一个。
2、不能把基本数字V 、L 、D 中的任何一个作为小数放在大数的左边采用相减的方法构成数目;放在大数的右边采用相加的方式构成数目,只能使用一个。
3、V 和X 左边的小数字只能用Ⅰ。
4、L 和C 左边的小数字只能用X。
5、D 和M 左边的小数字只能用C。
转自:Grandyang
 1 class Solution {
 2 public:
 3     int romanToInt(string s) {
 4         int n = s.size();
 5         int res = 0;
 6         unordered_map<char, int> map = { { I , 1 },
 7                                    { V , 5 },
 8                                    { X , 10 },
 9                                    { L , 50 },
10                                    { C , 100 },
11                                    { D , 500 },
12                                    { M , 1000 } };
13         for (int i = 0; i < n; ++i) {
14             int num = map[s[i]];
15             if (i == n - 1 || map[s[i + 1]] <= map[s[i]])
16                 res += num;
17             else
18                 res -= num;
19         }
20         
21         return res;
22     }
23 };

 

【LeetCode】013. Roman to Integer

标签:ble   com   数字   post   相加   rip   tco   blank   www   

原文地址:https://www.cnblogs.com/Atanisi/p/8645261.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!