Given a roman numeral, convert it to an integer.

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

 

首先,学习一下罗马数字,参考罗马数字 
罗马数字是最古老的数字表示方式,比阿拉伯数组早2000多年,起源于罗马 
罗马数字有如下符号: 

基本字符 I V X L C D M
对应阿拉伯数字 1 5 10 50 100 500 1000

计数规则: 相同的数字连写,所表示的数等于这些数字相加得到的数,例如:III = 3小的数字在大的数字右边,所表示的数等于这些数字相加得到的数,例如:VIII = 8小的数字,限于(I、X和C)在大的数字左边,所表示的数等于大数减去小数所得的数,例如:IV = 4正常使用时,连续的数字重复不得超过三次在一个数的上面画横线,表示这个数扩大1000倍(本题只考虑3999以内的数,所以用不到这条规则) 
其次,罗马数字转阿拉伯数字规则(仅限于3999以内): 

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

 

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

 

 

Integer to Roman:

 

 1 class Solution {
 2 public:
 3     string intToRoman(int num) {
 4         string str;  
 5         string symbol[]={"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};  
 6         int value[]=    {1000,900,500,400, 100, 90,  50, 40,  10, 9,   5,  4,   1}; 
 7         for(int i=0;num!=0;++i)
 8         {
 9             while(num>=value[i])
10             {
11                 num-=value[i];
12                 str+=symbol[i];
13             }
14         }
15         return str;
16     }
17 };

 

posted on 2015-04-18 19:38  黄瓜小肥皂  阅读(181)  评论(0编辑  收藏  举报