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

Roman to Integer

时间:2016-09-29 07:50:37      阅读:216      评论: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         if (s.empty()) return 0;
 5         
 6         int result = 0;
 7         int n = s.size();
 8         unordered_map<char, int> roman;
 9         roman[‘I‘] = 1;
10         roman[‘V‘] = 5;
11         roman[‘X‘] = 10;
12         roman[‘L‘] = 50;
13         roman[‘C‘] = 100;
14         roman[‘D‘] = 500;
15         roman[‘M‘] = 1000;
16         
17         for (int i = 0; i < n; i++) {
18             if (i < n - 1) {
19                 if (s[i] == ‘I‘ && s[i + 1] == ‘V‘) {result += 4; i++;}
20                 else if (s[i] == ‘I‘ && s[i + 1] == ‘X‘) {result += 9; i++;}
21                 else if (s[i] == ‘X‘ && s[i + 1] == ‘L‘) {result += 40; i++;}
22                 else if (s[i] == ‘X‘ && s[i + 1] == ‘C‘) {result += 90; i++;}
23                 else if (s[i] == ‘C‘ && s[i + 1] == ‘D‘) {result += 400; i++;}
24                 else if (s[i] == ‘C‘ && s[i + 1] == ‘M‘) {result += 900; i++;}
25                 else result += roman[s[i]];
26             }
27             else {
28                 result += roman[s[i]];
29             }
30         }
31         return result;
32     }
33 };

 

Roman to Integer

标签:

原文地址:http://www.cnblogs.com/amazingzoe/p/5918545.html

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