-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathroman_to_integer.cpp
More file actions
88 lines (82 loc) · 1.83 KB
/
Copy pathroman_to_integer.cpp
File metadata and controls
88 lines (82 loc) · 1.83 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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#include<bits/stdc++.h>
using namespace std;
int romanToInt(string s){
int num=0,i=0;
while(i<s.length()){
if(s[i]=='M'){
num+=1000;
i++;
}else if(s[i]=='D'){
num+=500;
i++;
}else if(s[i]=='C'){
if(i!=s.length()-1){
if(s[i+1]=='M'){
num+=900;
i+=2;
}else if(s[i+1]=='D'){
num+=400;
i+=2;
}else{
num+=100;
i++;
}
}else{
num+=100;
i++;
}
}else if(s[i]=='L'){
num+=50;
i++;
}else if(s[i]=='X'){
if(i!=s.length()-1){
if(s[i+1]=='L'){
num+=40;
i+=2;
}else if(s[i+1]=='C'){
num+=90;
i+=2;
}else{
num+=10;
i++;
}
}else{
num+=10;
i++;
}
}else if(s[i]=='V'){
num+=5;
i++;
}else if(s[i]=='I'){
if(i!=s.length()-1){
if(s[i+1]=='V'){
num+=4;
i+=2;
}else if(s[i+1]=='X'){
num+=9;
i+=2;
}else{
num+=1;
i++;
}
}else{
num+=1;
i++;
}
}
}
return num;
}
int main(){
string s="III";
cout<<romanToInt(s)<<endl;
s="IV";
cout<<romanToInt(s)<<endl;
s="IX";
cout<<romanToInt(s)<<endl;
s="LVIII";
cout<<romanToInt(s)<<endl;
s="MCMXCIV";
cout<<romanToInt(s)<<endl;
return 0;
}