Skip to content

Commit c14af04

Browse files
committed
Add Roman To Integer conversion
1 parent 53b2b69 commit c14af04

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed

Conversions/RomanToInteger.java

+60
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
import java.util.*;
2+
public class RomanToInteger {
3+
4+
/*
5+
This function convert Roman number into Integer
6+
@param A is Roman number string
7+
*/
8+
public static int romanToInt(String A) {
9+
Map<Character , Integer> map = new HashMap<>();
10+
map.put('I' , 1);
11+
map.put('V' , 5);
12+
map.put('X' , 10);
13+
map.put('L' , 50);
14+
map.put('C' , 100);
15+
map.put('D' , 500);
16+
map.put('M' , 1000);
17+
18+
char c = A.charAt(A.length()-1);
19+
char prev = ' ';
20+
21+
int sum =0;
22+
23+
int newPrev = 0, currentNum =0;
24+
for(int i = A.length() -1;i>=0;i--)
25+
{
26+
c = A.charAt(i);
27+
28+
29+
if(prev != ' ') {
30+
//checking current Number greater then previous or not
31+
newPrev = map.get(prev) > newPrev ? map.get(prev) : newPrev ;
32+
}
33+
34+
35+
currentNum = map.get(c);
36+
37+
if(currentNum >= newPrev ) //if current number greater then prev max previous then add
38+
{
39+
sum += currentNum;
40+
}
41+
else {
42+
43+
sum -= currentNum; // subtract upcoming number until upcoming number not greater then prev max
44+
}
45+
46+
prev = c;
47+
}
48+
49+
return sum;
50+
}
51+
52+
53+
public static void main(String[] args) {
54+
55+
56+
int sum = romanToInt("MDCCCIV") ;
57+
System.out.println(sum);
58+
}
59+
60+
}

0 commit comments

Comments
 (0)