-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path13-Roman-to-Integer.cpp
More file actions
30 lines (28 loc) · 997 Bytes
/
Copy path13-Roman-to-Integer.cpp
File metadata and controls
30 lines (28 loc) · 997 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
// # 13. Roman to Integer https://leetcode.com/problems/roman-to-integer/
// # level: easy
// # complexity: O(n) time, O(1) space, where n is len(s)
// rewriting my python code in cpp to brush up my cpp
class Solution {
public:
int romanToInt(string s) {
if (s.empty()) return 0; // check if the string is empty before use s.back()
unordered_map<char, int> table = { { 'I' , 1 },
{ 'V' , 5 },
{ 'X' , 10 },
{ 'L' , 50 },
{ 'C' , 100 },
{ 'D' , 500 },
{ 'M' , 1000 } };
int sum = 0;
for (int i = 0; i < s.length(); i++) {
// e.g. IV = -1 + 5 = 4
if (table[s[i]] < table[s[i + 1]]) {
sum -= table[s[i]];
}
else {
sum += table[s[i]];
}
}
return sum;
}
};