-
Notifications
You must be signed in to change notification settings - Fork 0
/
roman_to_int.cpp
65 lines (50 loc) · 1.42 KB
/
roman_to_int.cpp
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
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int romanToInt(string s) {
unordered_map<string, int> convertMap;
convertMap["I"] = 1;
convertMap["V"] = 5;
convertMap["X"] = 10;
convertMap["L"] = 50;
convertMap["C"] = 100;
convertMap["D"] = 500;
convertMap["M"] = 1000;
convertMap["IV"] = 4;
convertMap["IX"] = 9;
convertMap["XL"] = 40;
convertMap["XC"] = 90;
convertMap["CD"] = 400;
convertMap["CM"] = 900;
int sum=0;
int n = s.length();
if (n==1){
return convertMap[s];
}
bool last_is_pair = convertMap.find(s.substr(n-2)) != convertMap.end();
//true if the last form a pair
int i;
for (i=0;i<n-1;i++){
string two_char = s.substr(i,2);
if (convertMap.find(two_char)!=convertMap.end()){
//pair found for subtraction
sum = sum+convertMap[two_char];
i++;
}
else {
string first_letter = string(1,s[i]);
sum = sum+convertMap[first_letter];
}
}
if (!last_is_pair){
sum+=convertMap[string(1,s[n-1])];
}
return sum;
}
};
int main(){
Solution s;
cout<<s.romanToInt("D");
return 0;
}