首页 > 其他 > 详细

[LeetCode]Roman to Integer

时间:2015-11-12 19:58:59      阅读:261      评论:0      收藏:0      [点我收藏+]

题目描述:(链接)

Given a roman numeral, convert it to an integer.

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

解题思路:

 1 class Solution {
 2 public:
 3     int romanToInt(string s) {
 4         int len = s.size();
 5         if (len < 1) return 0;
 6         
 7         int result = 0;
 8         int sub = getRomanValue(s[0]);
 9         int lastV = sub;
10         for (int i = 1; i < len; ++i) {
11             char curC = s[i];
12             int curV = getRomanValue(curC);
13             if (curV == lastV) {
14                 sub += curV;
15             } else if (curV < lastV) {
16                 result += sub;
17                 sub = curV;
18             } else {
19                 sub = curV - lastV;
20             }
21             lastV = curV;
22         }
23         
24         result += sub;
25         return result;
26     }
27 private:
28     int getRomanValue(char c) {
29         switch(c) {
30             case I: return 1; 
31             case V: return 5;
32             case X: return 10;
33             case L: return 50;
34             case C: return 100;
35             case D: return 500;
36             case M: return 1000;
37             default: return 0;
38         }
39     }
40 };

 

[LeetCode]Roman to Integer

原文:http://www.cnblogs.com/skycore/p/4959856.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!