-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path13_roman_to_integer.cpp
More file actions
73 lines (64 loc) · 1.72 KB
/
13_roman_to_integer.cpp
File metadata and controls
73 lines (64 loc) · 1.72 KB
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
class Solution {
public:
int romanToInt(string s) {
//Check if the number is negative
bool negative = false;
if (s[0] == '-') {
negative = true;
}
//Initialize the total to 0 and the index to 0 or 1 if the string starts with a negative sign
int total(0);
int startIndex(0);
if (negative) {
startIndex = 1;
}
for (int i = startIndex; i < s.size() - 1; i++) {
int nA = charToRoman(s[i]);
int nB = charToRoman(s[i + 1]);
//If nA is greater than or equal to the next digit in the string.
if (nA >= nB) {
total += nA;
}
//Otherwise remove nA from the total.
else total -= nA;
}
//Last number
total += charToRoman(s[s.size() - 1]);
//Return the solution.
if(negative) {
return - total;
} else return total;
}
//Function that returns an int from a roman character.
int charToRoman(char c) {
//Defining constants for each roman digit.
const int M(1000), D(500), C(100), L(50), X(10), V(5), I(1);
switch (c)
{
case 'I':
return I;
break;
case 'V':
return V;
break;
case 'X':
return X;
break;
case 'L':
return L;
break;
case 'C':
return C;
break;
case 'D':
return D;
break;
case 'M':
return M;
break;
default:
return 0;
break;
}
}
};