Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Map;
- import java.util.SortedMap;
- import java.util.TreeMap;
- /**
- * @author deliveryninja
- *
- * Given a numeral from 1 to 3000 this will return the Roman
- * numberal equivalent.
- *
- * @param numeral
- * @return
- */
- public class Roman {
- public enum RomanNumeral{
- M(1000),
- CM(900),
- D(500),
- CD(400),
- C(100),
- XC(90),
- L(50),
- XL(40),
- X(10),
- IX(9),
- V(5),
- IV(4),
- I(1);
- private int value;
- RomanNumeral(int value){
- this.value = value;
- }
- public int getIntegerValue() {
- return value;
- }
- }
- public String romanize(int numeral) {
- StringBuffer result = new StringBuffer();
- for(RomanNumeral romanNumeral : RomanNumeral.values()){
- while(numeral >= romanNumeral.getIntegerValue()){
- result.append(romanNumeral);
- numeral -= romanNumeral.getIntegerValue();
- }
- }
- return result.toString();
- }
- public int convertToNumeral(String input) {
- int result = 0;
- //Loop left to right across the input number
- for(int index = 0; index < input.length() ; index++){
- //Check the current value with all known roman values
- for(RomanNumeral romanNumeral : RomanNumeral.values()){
- //Check if the next value is 1 or 2 characters long
- int adjustedIndex = calculateIndexPosition(romanNumeral, index+1, input.length());
- //Compare the input and current roman numeral
- if(input.substring(index, adjustedIndex).equals(romanNumeral.toString())){
- result += romanNumeral.getIntegerValue(); //Increment the result
- //Increment the index so we don't re-evaluate the same characters
- index = adjustedIndex - 1;
- }
- }
- }
- return result;
- }
- private int calculateIndexPosition(RomanNumeral romanNumeral, int index, int inputLength){
- //Check if the length is larger than 1 and there is more than 1 character in the input
- if(romanNumeral.toString().length() > 1 && index < inputLength){
- index++; //Increment index to check 2 characters
- }
- return index;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment