Skip to content

Commit 2b406e0

Browse files
authored
Merge pull request #2954 from aviralrabbit1/cpp0013
create: 0013-roman-to-integer.cpp
2 parents 3d15503 + 7450258 commit 2b406e0

File tree

1 file changed

+87
-0
lines changed

1 file changed

+87
-0
lines changed

cpp/0013-roman-to-integer.cpp

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
/*Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
2+
3+
Symbol Value
4+
I 1
5+
V 5
6+
X 10
7+
L 50
8+
C 100
9+
D 500
10+
M 1000
11+
For example, 2 is written as II in Roman numeral, just two ones added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II.
12+
13+
Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:
14+
15+
I can be placed before V (5) and X (10) to make 4 and 9.
16+
X can be placed before L (50) and C (100) to make 40 and 90.
17+
C can be placed before D (500) and M (1000) to make 400 and 900.
18+
Given a roman numeral, convert it to an integer.
19+
Example 3:
20+
21+
Input: s = "MCMXCIV"
22+
Output: 1994
23+
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4. */
24+
25+
int prec(char x){
26+
switch(x){
27+
case 'I':
28+
return 1;
29+
case 'V':
30+
return 2;
31+
case 'X':
32+
return 3;
33+
case 'L':
34+
return 4;
35+
case 'C':
36+
return 5;
37+
case 'D':
38+
return 6;
39+
case 'M':
40+
return 7;
41+
default:
42+
return -1;
43+
}
44+
}
45+
46+
int val(char x){
47+
switch(x){
48+
case 'I':
49+
return 1;
50+
case 'V':
51+
return 5;
52+
case 'X':
53+
return 10;
54+
case 'L':
55+
return 50;
56+
case 'C':
57+
return 100;
58+
case 'D':
59+
return 500;
60+
case 'M':
61+
return 1000;
62+
default:
63+
return -1;
64+
}
65+
}
66+
67+
class Solution {
68+
public:
69+
70+
int romanToInt(string s)
71+
{
72+
int ans = 0;
73+
74+
for(int i=0; i<s.length(); i++){
75+
if(prec(s[i]) >= prec(s[i+1])){
76+
ans += val(s[i]);
77+
}
78+
else if(prec(s[i]) < prec(s[i+1])){
79+
ans = ans - val(s[i]) + val(s[i+1]);
80+
i++;
81+
}
82+
}
83+
84+
return ans;
85+
}
86+
87+
};

0 commit comments

Comments
 (0)