Skip to content

Commit 3e21fe4

Browse files
committed
Convert roman number to decimal number: 1st commit
1 parent 659e1cf commit 3e21fe4

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

string/RomanToDecimal.java

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
package string;
2+
3+
public class RomanToDecimal {
4+
5+
private int getDecimalValue(char ch) {
6+
if(ch == 'I')
7+
return 1;
8+
if(ch == 'V')
9+
return 5;
10+
if(ch == 'X')
11+
return 10;
12+
if(ch == 'L')
13+
return 50;
14+
if(ch == 'C')
15+
return 100;
16+
if(ch == 'D')
17+
return 500;
18+
if(ch == 'M')
19+
return 1000;
20+
return -1;
21+
}
22+
23+
private int getDecimal(String roman) {
24+
int decimal = 0;
25+
int length = roman.length();
26+
for(int i=0; i<length; i++) {
27+
int num1 = getDecimalValue(roman.charAt(i));
28+
if(i+1 < length) {
29+
int num2 = getDecimalValue(roman.charAt(i+1));
30+
if(num1 < num2) {
31+
decimal += num2 - num1;
32+
i++;
33+
} else {
34+
decimal += num1;
35+
}
36+
} else {
37+
decimal += num1;
38+
i++;
39+
}
40+
}
41+
return decimal;
42+
}
43+
44+
public static void main(String[] args) {
45+
// TODO Auto-generated method stub
46+
RomanToDecimal obj = new RomanToDecimal();
47+
System.out.println(obj.getDecimal("DIX"));
48+
}
49+
50+
}

0 commit comments

Comments
 (0)