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

[Leetcode] Roman to integer 罗马数字转成整数

时间:2017-06-20 16:25:02      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:from   style   思路   罗马数字转换   const   解决办法   roman   数字   solution   

Given a roman numeral, convert it to an integer.

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

思路:有关罗马数字的相关知识可见博客Integer to roman。从左往右遍历字符串,比较当前为和下一位的值,若是当前数字比下一位大,或者当当前数字为最后时,则加上当前数字,否则减去当前数字。这就遇到一个问题,罗马数字的字符串不是按26个字母顺序来的,如何确定大小。解决办法一:写一个函数,将罗马数字转换成整数,然后进行比较;解法二,可以使用map数据结构,将罗马数字的字母转换成对应的整数值。

方法一的代码如下:

 1 class Solution {
 2 public:
 3     int romanToInt(string s) 
 4     {
 5         int res=0;    //记得初始化
 6         for(int i=0;i<s.size();++i)
 7         {
 8             if(i==s.size()-1||strToNum(s[i])>=strToNum(s[i+1]))
 9                 res+=strToNum(s[i]);
10             else
11                 res-=strToNum(s[i]);
12         }   
13         return res;
14     }
15 
16     int strToNum(const char c)
17     {
18         int num=0;
19         switch(c)
20         {
21             case M:
22                 num=1000;
23                 break;
24             case D:
25                 num=500;
26                 break;
27             case C:
28                 num=100;
29                 break;
30             case L:
31                 num=50;
32                 break;
33             case X:
34                 num=10;
35                 break;
36             case V:
37                 num=5;
38                 break;
39             case I:
40                 num=1;
41                 break;
42             default:
43                 num=0;
44         }
45         return num;
46     }
47 };

 

方法二:

 1 class Solution {
 2 public:
 3     int romanToInt(string s) {
 4         int res = 0;
 5         unordered_map<char, int> m{{I, 1}, {V, 5}, {X, 10}, {L, 50}, {C, 100}, {D, 500}, {M, 1000}};
 6         for (int i = 0; i < s.size(); ++i) 
 7         {
 8             
 9             if (i == s.size() - 1 || m[s[i]] >= m[s[i+1]]) 
10                 res += m[s[i]];
11             else 
12                 res -= m[s[i]];
13         }
14         return res;
15     }
16 };

[Leetcode] Roman to integer 罗马数字转成整数

标签:from   style   思路   罗马数字转换   const   解决办法   roman   数字   solution   

原文地址:http://www.cnblogs.com/love-yh/p/7054460.html

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