13. 罗马数字转整数
为保证权益,题目请参考 13. 罗马数字转整数(From LeetCode).
解决方案1
CPP
C++
#include <iostream>
#include <string>
using namespace std;
class Solution {
public:
int romanToInt(string s) {
if (s.empty()) {
return 0;
} else {
char ch = s[0];
int val;
int si = 1;
if (ch == 'M') {
val = 1000;
} else if (ch == 'D') {
val = 500;
} else if (ch == 'C') {
if (s.length() > 1) {
char ch2 = s[1];
if (ch2 == 'M') {
val = 900;
si = 2;
} else if (ch2 == 'D') {
val = 400;
si = 2;
} else {
val = 100;
}
} else {
val = 100;
}
} else if (ch == 'L') {
val = 50;
} else if (ch == 'X') {
if (s.length() > 1) {
char ch2 = s[1];
if (ch2 == 'C') {
val = 90;
si = 2;
} else if (ch2 == 'L') {
val = 40;
si = 2;
} else {
val = 10;
}
} else {
val = 10;
}
} else if (ch == 'V') {
val = 5;
} else if (ch == 'I') {
if (s.length() > 1) {
char ch2 = s[1];
if (ch2 == 'X') {
val = 9;
si = 2;
} else if (ch2 == 'V') {
val = 4;
si = 2;
} else {
val = 1;
}
} else {
val = 1;
}
}
return val + romanToInt(s.substr(si));
}
}
};
int main() {
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76