-
Notifications
You must be signed in to change notification settings - Fork 0
/
13. Roman to Integer.cpp
61 lines (59 loc) · 1.56 KB
/
13. Roman to Integer.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
/*
Problem Description:
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
*/
class Solution {
public:
int romanToInt(string s) {
int result=0;
for(int i=0;i!=s.size();i++)
{
switch(s[i])
{
case 'I':
if(s[i+1]=='V' || s[i+1]=='X')
{
result--;
}
else
{
result++;
}
break;
case 'V':
result+=5;
break;
case 'X':
if(s[i+1]=='L' || s[i+1]=='C')
{
result-=10;
}
else
{
result+=10;
}
break;
case 'L':
result+=50;
break;
case 'C':
if(s[i+1]=='D' || s[i+1]=='M')
{
result-=100;
}
else
{
result+=100;
}
break;
case 'D':
result+=500;
break;
case 'M':
result+=1000;
}
}
return result;
}
};