Skip to content

Commit 971d5f7

Browse files
authored
Format code in RomanToInteger.java
* Format code * Remove redundant code
1 parent c14af04 commit 971d5f7

File tree

1 file changed

+51
-55
lines changed

1 file changed

+51
-55
lines changed

Conversions/RomanToInteger.java

Lines changed: 51 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -1,60 +1,56 @@
11
import java.util.*;
2+
23
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-
}
514

5+
private static Map<Character, Integer> map = new HashMap<>() {{
6+
put('I', 1);
7+
put('V', 5);
8+
put('X', 10);
9+
put('L', 50);
10+
put('C', 100);
11+
put('D', 500);
12+
put('M', 1000);
13+
}};
14+
15+
/**
16+
* This function convert Roman number into Integer
17+
*
18+
* @param A Roman number string
19+
* @return integer
20+
*/
21+
public static int romanToInt(String A) {
22+
23+
char prev = ' ';
24+
25+
int sum = 0;
26+
27+
int newPrev = 0;
28+
for (int i = A.length() - 1; i >= 0; i--) {
29+
char c = A.charAt(i);
5230

53-
public static void main(String[] args) {
54-
55-
56-
int sum = romanToInt("MDCCCIV") ;
57-
System.out.println(sum);
58-
}
31+
if (prev != ' ') {
32+
// checking current Number greater then previous or not
33+
newPrev = map.get(prev) > newPrev ? map.get(prev) : newPrev;
34+
}
5935

60-
}
36+
int currentNum = map.get(c);
37+
38+
// if current number greater then prev max previous then add
39+
if (currentNum >= newPrev) {
40+
sum += currentNum;
41+
} else {
42+
// subtract upcoming number until upcoming number not greater then prev max
43+
sum -= currentNum;
44+
}
45+
46+
prev = c;
47+
}
48+
49+
return sum;
50+
}
51+
52+
public static void main(String[] args) {
53+
int sum = romanToInt("MDCCCIV");
54+
System.out.println(sum);
55+
}
56+
}

0 commit comments

Comments
 (0)