首页 > 其他 > 详细

[Leetcode] Roman to Integer

时间:2014-04-11 06:35:41      阅读:457      评论:0      收藏:0      [点我收藏+]

Given a roman numeral, convert it to an integer.

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

纯模拟,规则见:Integer to Roman

bubuko.com,布布扣
 1 class Solution {
 2 public:
 3     map<char, int> roman;
 4     void init() {
 5         roman[I] = 1;
 6         roman[V] = 5;
 7         roman[X] = 10;
 8         roman[L] = 50;
 9         roman[C] = 100;
10         roman[D] = 500;
11         roman[M] = 1000;
12     }
13     
14     bool check(char a, char b) {
15         return roman[a] < roman[b];
16     }
17     
18     int romanToInt(string s) {
19         init();
20         int res = 0;
21         for (int i = 0; i < s.length(); ++i) {
22             if (i > 0 && check(s[i-1], s[i])) {
23                 res -= 2 * roman[s[i-1]];
24             }
25             res += roman[s[i]];
26         }
27         return res;
28     }
29 };
bubuko.com,布布扣

 

[Leetcode] Roman to Integer,布布扣,bubuko.com

[Leetcode] Roman to Integer

原文:http://www.cnblogs.com/easonliu/p/3656952.html

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