Skip to content

Instantly share code, notes, and snippets.

@alebaffa
Last active July 4, 2016 22:27
Show Gist options
  • Save alebaffa/a9111713ec0e3b6f6647e5ab6af6d4f1 to your computer and use it in GitHub Desktop.
Save alebaffa/a9111713ec0e3b6f6647e5ab6af6d4f1 to your computer and use it in GitHub Desktop.
public class RomanNumbers {
// LinkedHashMap allows the fetch of the items in the same order of the insert
private static Map<Integer, String> dictionary = new LinkedHashMap<>();
static {
dictionary.put(50, "L");
dictionary.put(40, "XL");
dictionary.put(10, "X");
dictionary.put(9, "IX");
dictionary.put(5, "V");
dictionary.put(4, "IV");
dictionary.put(1, "I");
};
public String convertToRoman(int number) {
String result = "";
Iterator iterator = dictionary.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry pair = (Map.Entry) iterator.next();
Integer arabicNumber = (Integer) pair.getKey();
String romanNumber = (String) pair.getValue();
while (number >= arabicNumber) {
result += romanNumber;
number -= arabicNumber;
}
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment