-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathroman-to-integer.cpp
More file actions
45 lines (43 loc) · 945 Bytes
/
Copy pathroman-to-integer.cpp
File metadata and controls
45 lines (43 loc) · 945 Bytes
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
class Solution {
public:
int num(char c) {
if (c == 'I') {
return 1;
}
if (c == 'V') {
return 5;
}
if (c == 'X') {
return 10;
}
if (c == 'L') {
return 50;
}
if (c == 'C') {
return 100;
}
if (c == 'D') {
return 500;
}
if (c == 'M') {
return 1000;
}
return 0;
}
int romanToInt(string s) {
int sum = 0;
int index = 0;
int n = s.size();
while (index < n-1) {
if (num(s[index]) >= num(s[index + 1])) {
sum += num(s[index]);
index++;
} else {
sum -= num(s[index]);
index++;
}
}
sum += num(s[index]);
return sum;
}
};