Skip to content

Commit 93ad3cc

Browse files
committed
feat: menambahkan koversi romawi ke integer
close #44 Signed-off-by: slowy07 <[email protected]>
1 parent 3c6254b commit 93ad3cc

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

Diff for: conversion/RomanToInteger.java

+51
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
import java.util.*;
2+
3+
public class RomanToInteger{
4+
private static Map<Character, Integer> map =
5+
new HashMap<Character, Integer> (){
6+
private static final long serialVersionUID = 87605733047260530L;
7+
{
8+
put('I', 1);
9+
put('V', 5);
10+
put('X', 10);
11+
put('L', 50);
12+
put('C', 100);
13+
put('D', 500);
14+
put('M', 1000);
15+
}
16+
};
17+
18+
/**
19+
* fungsi yang akan merubah dari angka romawi ke Integer
20+
* @param string dari angka romawi
21+
* @return Integer
22+
*/
23+
24+
public static int RomanToInt(String A){
25+
A = A.toUpperCase();
26+
char prev = ' ';
27+
int sum = 0;
28+
int newPrev = 0;
29+
for(int i = A.length() - 1; i >= 0; i--){
30+
char c = A.charAt(i);
31+
if (prev != ' '){
32+
newPrev = map.get(prev) > newPrev ? map.get(prev) : newPrev;
33+
}
34+
int currentNum = map.get(c);
35+
36+
if (currentNum >= newPrev){
37+
sum += currentNum;
38+
}
39+
else{
40+
sum -= currentNum;
41+
}
42+
prev = c;
43+
}
44+
return sum;
45+
}
46+
47+
public static void main(String[] args){
48+
int sum = RomanToInt("MDCCIV");
49+
System.out.println(sum);
50+
}
51+
}

0 commit comments

Comments
 (0)