Skip to content

Commit 95db854

Browse files
authored
Create roman-to-integer.cpp
1 parent ed8d912 commit 95db854

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

C++/roman-to-integer.cpp

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
// Time: O(n)
2+
// Space: O(1)
3+
4+
class Solution {
5+
public:
6+
int romanToInt(string s) {
7+
unordered_map<char, int> numeral_map = {{'I', 1}, {'V', 5}, {'X', 10},
8+
{'L', 50}, {'C', 100}, {'D', 500},
9+
{'M', 1000}};
10+
int decimal = 0;
11+
for (int i = 0; i < s.length(); ++i) {
12+
if (i > 0 && numeral_map[s[i]] > numeral_map[s[i - 1]]) {
13+
decimal += numeral_map[s[i]] - 2 * numeral_map[s[i - 1]];
14+
} else {
15+
decimal += numeral_map[s[i]];
16+
}
17+
}
18+
return decimal;
19+
}
20+
};

0 commit comments

Comments
 (0)