Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Part5 {
- // 1 - I
- // 5 - V
- // 10 - X
- // 50 - L
- // 100 - C
- // 500 - D
- // 1000- M
- public static void main(String[] args) {
- // System.out.println(roman2Decimal("MMMCMXCIX"));
- // System.out.println(decimal2Roman(3999));
- long startTime = System.currentTimeMillis();
- for(int a = 0; a < 1000000; a++) {
- Part5.roman2Decimal("IV");
- Part5.decimal2Roman(4);
- Part5.roman2Decimal("XCIV");
- Part5.decimal2Roman(94);
- Part5.roman2Decimal("XCV");
- Part5.decimal2Roman(95);
- Part5.roman2Decimal("XCVI");
- Part5.decimal2Roman(96);
- Part5.roman2Decimal("XCVII");
- Part5.decimal2Roman(97);
- Part5.roman2Decimal("XCVIII");
- Part5.decimal2Roman(98);
- Part5.roman2Decimal("XCIX");
- Part5.decimal2Roman(99);
- Part5.roman2Decimal("C");
- Part5.decimal2Roman(100);
- }
- long timeSpent = System.currentTimeMillis() - startTime;
- System.out.println("программа выполнялась " + timeSpent + " миллисекунд");
- }
- public static int roman2Decimal(String s) {
- int Decimal = 0;
- char Previous = 0;
- for (int x = 0; x < s.length(); x++) {
- if (s.charAt(x) == 'I')
- Decimal += 1;
- if (s.charAt(x) == 'V') {
- if (Previous == 'I') {
- Decimal -= 2;
- }
- Decimal += 5;
- }
- if (s.charAt(x) == 'X') {
- if (Previous == 'I') {
- Decimal -= 2;
- }
- Decimal += 10;
- }
- if (s.charAt(x) == 'L') {
- if (Previous == 'X') {
- Decimal -= 20;
- }
- Decimal += 50;
- }
- if (s.charAt(x) == 'C') {
- if (Previous == 'X') {
- Decimal -= 20;
- }
- Decimal += 100;
- }
- if (s.charAt(x) == 'D') {
- if (Previous == 'C') {
- Decimal -= 200;
- }
- Decimal += 500;
- }
- if (s.charAt(x) == 'M') {
- if (Previous == 'C') {
- Decimal -= 200;
- }
- Decimal += 1000;
- }
- Previous = s.charAt(x);
- }
- return Decimal;
- }
- public static String decimal2Roman(int x) {
- if (x >= 4000 || x <= 0)
- return null;
- StringBuilder result = new StringBuilder();
- for (Integer key : units.descendingKeySet()) {
- while (x >= key) {
- x -= key;
- result.append(units.get(key));
- }
- }
- return result.toString();
- }
- private static final NavigableMap<Integer, String> units;
- static {
- NavigableMap<Integer, String> initMap = new TreeMap<>();
- initMap.put(1000, "M");
- initMap.put(900, "CM");
- initMap.put(500, "D");
- initMap.put(400, "CD");
- initMap.put(100, "C");
- initMap.put(90, "XC");
- initMap.put(50, "L");
- initMap.put(40, "XL");
- initMap.put(10, "X");
- initMap.put(9, "IX");
- initMap.put(5, "V");
- initMap.put(4, "IV");
- initMap.put(1, "I");
- units = Collections.unmodifiableNavigableMap(initMap);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement