Advertisement
JovanPapi

[NP - lab1] Rimski broevi

Oct 25th, 2019
148
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.57 KB | None | 0 0
  1. import java.util.Scanner;
  2. import java.util.TreeMap;
  3. import java.util.stream.IntStream;
  4.  
  5. class RomanConverter {
  6.  
  7.     private static final TreeMap<Integer, String> mapper = new TreeMap<>();
  8.  
  9.     static {
  10.         mapper.put(1, "I");
  11.         mapper.put(4, "IV");
  12.         mapper.put(5, "V");
  13.         mapper.put(9, "IX");
  14.         mapper.put(10, "X");
  15.         mapper.put(40, "XL");
  16.         mapper.put(50, "L");
  17.         mapper.put(90, "XC");
  18.         mapper.put(100, "C");
  19.         mapper.put(400, "CD");
  20.         mapper.put(500, "D");
  21.         mapper.put(900, "CM");
  22.         mapper.put(1000, "M");
  23.     }
  24.  
  25.     public RomanConverter() {
  26.     }
  27.  
  28.     public static String toRoman(int numberToRoman) {
  29.         int n = mapper.floorKey(numberToRoman);
  30.  
  31.         /* We get the greatest key that's less than or same as the numberToRoman
  32.            If it's same, ex. 1000 then return only " M " and stop.*/
  33.         if (numberToRoman == n) {
  34.             return mapper.get(numberToRoman);
  35.         }
  36.  
  37.         /* if numberToRoman is not same with any of the keys
  38.          then get the value of greatest found key and call back the func.
  39.          with the numberToRoman substracted with the key :)*/
  40.         return mapper.get(n) + toRoman(numberToRoman - n);
  41.     }
  42. }
  43.  
  44. public class RomanConverterTest {
  45.     public static void main(String[] args) {
  46.  
  47.         Scanner insert = new Scanner(System.in);
  48.  
  49.         IntStream.range(0, insert.nextInt())
  50.                 .forEach(iteration -> System.out.println(RomanConverter.toRoman(insert.nextInt())));
  51.  
  52.         insert.close();
  53.     }
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement