Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- import java.util.TreeMap;
- import java.util.stream.IntStream;
- class RomanConverter {
- private static final TreeMap<Integer, String> mapper = new TreeMap<>();
- static {
- mapper.put(1, "I");
- mapper.put(4, "IV");
- mapper.put(5, "V");
- mapper.put(9, "IX");
- mapper.put(10, "X");
- mapper.put(40, "XL");
- mapper.put(50, "L");
- mapper.put(90, "XC");
- mapper.put(100, "C");
- mapper.put(400, "CD");
- mapper.put(500, "D");
- mapper.put(900, "CM");
- mapper.put(1000, "M");
- }
- public RomanConverter() {
- }
- public static String toRoman(int numberToRoman) {
- int n = mapper.floorKey(numberToRoman);
- /* We get the greatest key that's less than or same as the numberToRoman
- If it's same, ex. 1000 then return only " M " and stop.*/
- if (numberToRoman == n) {
- return mapper.get(numberToRoman);
- }
- /* if numberToRoman is not same with any of the keys
- then get the value of greatest found key and call back the func.
- with the numberToRoman substracted with the key :)*/
- return mapper.get(n) + toRoman(numberToRoman - n);
- }
- }
- public class RomanConverterTest {
- public static void main(String[] args) {
- Scanner insert = new Scanner(System.in);
- IntStream.range(0, insert.nextInt())
- .forEach(iteration -> System.out.println(RomanConverter.toRoman(insert.nextInt())));
- insert.close();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement