Untitled

mail@pastecode.io avatar
unknown
java
a year ago
1.3 kB
1
Indexable
Never
    public int romanToInt(String s) {
        Map<String, Integer> rim = new HashMap<>();
        rim.put("I", 1);
        rim.put("V", 5);
        rim.put("X", 10);
        rim.put("L", 50);
        rim.put("C", 100);
        rim.put("D", 500);
        rim.put("M", 1000);
        String[] mass = s.split("");

        int result = 0;
        for (int a = 0; a < mass.length; a++) {
            int num = rim.get(mass[a]);
            if (a != mass.length - 1 && num < rim.get(mass[a + 1])) {
                result -= num;
            } else {
                result += num;
            }
        }

        System.out.println(s + " " + result);

        return Stream.iterate(0, a -> a < mass.length - 1 ? a + 1 : a)
                .peek(x -> System.out.print("x = " + x + ", "))
                .map(i -> {
                    int b = rim.get(mass[i]);
                    if (i != mass.length - 1) {
                        System.out.println("i = " + i + ", mass.length = " + mass.length);
                        if (b < rim.get(mass[i + 1])) {
                            b *= -1;
                        }
                    }
                    return b;
                })
                .peek(y -> System.out.print("y = " + y + ", "))
                .reduce(0, Integer::sum);
    }