2019-05-09 19:32:54 +08:00
|
|
|
package Conversions;
|
|
|
|
|
2019-03-18 23:52:51 +08:00
|
|
|
import java.util.*;
|
2019-03-19 08:40:02 +08:00
|
|
|
|
2019-03-18 23:52:51 +08:00
|
|
|
public class RomanToInteger {
|
|
|
|
|
2020-10-24 18:23:28 +08:00
|
|
|
private static Map<Character, Integer> map =
|
|
|
|
new HashMap<Character, Integer>() {
|
|
|
|
/** */
|
2020-03-26 23:52:53 +08:00
|
|
|
private static final long serialVersionUID = 87605733047260530L;
|
|
|
|
|
|
|
|
{
|
2020-10-24 18:23:28 +08:00
|
|
|
put('I', 1);
|
|
|
|
put('V', 5);
|
|
|
|
put('X', 10);
|
|
|
|
put('L', 50);
|
|
|
|
put('C', 100);
|
|
|
|
put('D', 500);
|
|
|
|
put('M', 1000);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
// Roman Number = Roman Numerals
|
2019-03-19 08:40:02 +08:00
|
|
|
|
2020-10-24 18:23:28 +08:00
|
|
|
/**
|
|
|
|
* This function convert Roman number into Integer
|
|
|
|
*
|
|
|
|
* @param A Roman number string
|
|
|
|
* @return integer
|
|
|
|
*/
|
|
|
|
public static int romanToInt(String A) {
|
2019-03-19 08:40:02 +08:00
|
|
|
|
2020-10-24 18:23:28 +08:00
|
|
|
A = A.toUpperCase();
|
|
|
|
char prev = ' ';
|
2019-03-19 08:40:02 +08:00
|
|
|
|
2020-10-24 18:23:28 +08:00
|
|
|
int sum = 0;
|
2019-03-18 23:52:51 +08:00
|
|
|
|
2020-10-24 18:23:28 +08:00
|
|
|
int newPrev = 0;
|
|
|
|
for (int i = A.length() - 1; i >= 0; i--) {
|
|
|
|
char c = A.charAt(i);
|
2019-03-18 23:52:51 +08:00
|
|
|
|
2020-10-24 18:23:28 +08:00
|
|
|
if (prev != ' ') {
|
|
|
|
// checking current Number greater then previous or not
|
|
|
|
newPrev = map.get(prev) > newPrev ? map.get(prev) : newPrev;
|
|
|
|
}
|
2019-03-19 08:40:02 +08:00
|
|
|
|
2020-10-24 18:23:28 +08:00
|
|
|
int currentNum = map.get(c);
|
2019-03-19 08:40:02 +08:00
|
|
|
|
2020-10-24 18:23:28 +08:00
|
|
|
// if current number greater then prev max previous then add
|
|
|
|
if (currentNum >= newPrev) {
|
|
|
|
sum += currentNum;
|
|
|
|
} else {
|
|
|
|
// subtract upcoming number until upcoming number not greater then prev max
|
|
|
|
sum -= currentNum;
|
|
|
|
}
|
2019-03-19 08:40:02 +08:00
|
|
|
|
2020-10-24 18:23:28 +08:00
|
|
|
prev = c;
|
2019-03-19 08:40:02 +08:00
|
|
|
}
|
|
|
|
|
2020-10-24 18:23:28 +08:00
|
|
|
return sum;
|
|
|
|
}
|
|
|
|
|
|
|
|
public static void main(String[] args) {
|
|
|
|
int sum = romanToInt("MDCCCIV");
|
|
|
|
System.out.println(sum);
|
|
|
|
}
|
|
|
|
}
|