Created
June 11, 2020 21:22
-
-
Save theboreddev/12c4ded64b26536eefee94e255f60cca to your computer and use it in GitHub Desktop.
recursiveRomanNumerals
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class RomanNumerals { | |
private static final NavigableMap<Integer, String> ROMAN_NUMERALS = new TreeMap<>() { | |
{ | |
put(1, "I"); | |
put(5, "V"); | |
put(10, "X"); | |
put(50, "L"); | |
put(100, "C"); | |
put(500, "D"); | |
put(1000, "M"); | |
} | |
}; | |
public static String convert(int number) { | |
if (number == 0) return ""; | |
final String result = ROMAN_NUMERALS.get(number); | |
return result != null ? result : calculateRomanNumeral(number); | |
} | |
private static String calculateRomanNumeral(int number) { | |
final Integer lowerKey = ROMAN_NUMERALS.lowerKey(number); | |
return ROMAN_NUMERALS.get(lowerKey) + convert(number - lowerKey); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment