leetcode: Roman to Integer

http://oj.leetcode.com/problems/roman-to-integer/

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 val = 0, mul = 0;
 5         char one, five, ten;
 6         const char *p = s.c_str();
 7         
 8         while (*p != '\0') {
 9             char ch = *p;
10             
11             if ('M' == ch) {
12                 mul = 1000;
13                 one = 'M';
14                 five = '?';
15                 ten = '?';
16             }
17             else if (('C' == ch) || ('D' == ch)) {
18                 mul = 100;
19                 one = 'C';
20                 five = 'D';
21                 ten = 'M';
22             }
23             else if (('X' == ch) || ('L' == ch)) {
24                 mul = 10;
25                 one = 'X';
26                 five = 'L';
27                 ten = 'C';
28             }
29             else {  // 'I' or 'V'.
30                 mul = 1;
31                 one = 'I';
32                 five = 'V';
33                 ten = 'X';
34             }
35             
36             int tmp;
37             
38             if (one == ch) {
39                 tmp = 1;
40                 ++p;
41                 while ((*p != '\0') && (one == *p)) {
42                     ++tmp;
43                     ++p;
44                 }
45                 
46                 if (ten == *p) {
47                     val += (mul * 9);
48                     ++p;
49                 }
50                 else if (five == *p) {
51                     val += (mul * 4);
52                     ++p;
53                 }
54                 else {
55                     val += (mul * tmp);
56                 }
57             }
58             else if (five == ch) {
59                 tmp = 5;
60                 ++p;
61                 while ((*p != '\0') && (one == *p)) {
62                     ++tmp;
63                     ++p;
64                 }
65                 
66                 val += (mul * tmp);
67             }
68             // No need to handle ten, because it will be one in next level.
69         }
70         
71         return val;
72     }
73 };

 

posted @ 2013-10-28 14:12  移山测试工作室黑灯老师  阅读(450)  评论(0编辑  收藏  举报
count website visits
Buy Computers