Advertisement
Filip_Markoski

[NP] 1.1 Римски Броеви (Solved)

Oct 15th, 2017
704
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.58 KB | None | 0 0
  1. /*
  2. Да се напише метод кој ќе прима еден цел број и ќе ја печати неговата репрезентација како Римски број.
  3. Пример: Aко ако се повика со парамететар 1998, излезот треба да биде MCMXCVIII.
  4. */
  5.  
  6. import java.util.Scanner;
  7. import java.util.stream.IntStream;
  8. import java.lang.IllegalArgumentException;
  9.  
  10. public class RomanConverterTest {
  11.     public static void main(String[] args) {
  12.         Scanner scanner = new Scanner(System.in);
  13.         int n = scanner.nextInt();
  14.         IntStream.range(0, n)
  15.                 .forEach(x -> System.out.println(RomanConverter.toRoman(scanner.nextInt())));
  16.         scanner.close();
  17.     }
  18. }
  19.  
  20. class RomanConverter {
  21.     /**
  22.      * Roman to decimal converter
  23.      *
  24.      * @param n number in decimal format
  25.      * @return string representation of the number in Roman numeral
  26.      */
  27.     public static String toRoman(int n) {
  28.         /* Greedy Algorithm */
  29.  
  30.         StringBuffer sb = new StringBuffer();
  31.         int times = 0;
  32.         String[] romans = new String[] { "I", "IV", "V", "IX", "X", "XL", "L", "XC", "C", "CD", "D", "CM", "M" };
  33.         int[] integers = new int[] { 1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000 };
  34.         for (int i = integers.length - 1; i >= 0 ; i--) {
  35.             times = n / integers[i];
  36.             n %= integers[i];
  37.             while (times > 0){
  38.                 sb.append(romans[i]);
  39.                 times--;
  40.             }
  41.         }
  42.         return sb.toString();
  43.     }
  44.  
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement