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

【leetcode】Roman to Integer

时间:2014-12-25 00:03:39      阅读:266      评论:0      收藏:0      [点我收藏+]

标签:

Roman to Integer

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. 相同的数字连写,所表示的数等于这些数字相加得到的数,例如:III = 3
  2. 小的数字在大的数字右边,所表示的数等于这些数字相加得到的数,例如:VIII = 8
  3. 小的数字,限于(I、X和C)在大的数字左边,所表示的数等于大数减去小数所得的数,例如:IV = 4
  4. 正常使用时,连续的数字重复不得超过三次
  5. 在一个数的上面画横线,表示这个数扩大1000倍(本题只考虑3999以内的数,所以用不到这条规则)


从前向后遍历罗马数字,如果某个数比前一个数小,则加上该数。反之,减去前一个数的两倍然后加上该数

 

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

 

 

【leetcode】Roman to Integer

标签:

原文地址:http://www.cnblogs.com/reachteam/p/4183575.html

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