/
eelamimi
/
SberJavaCourseBeginner
Обзор
Документация
Войти
/
eelamimi
/
SberJavaCourseBeginner
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
Аналитика
Безопасность
cw_6
src/courseSber/leetCode/math/RomanToInt.java
40 строк
1 KB
glebka
8/100 leetcode tasks
16 июн 2025, 18:21
16 июн 2025, 18:21
23f39e2
Код
Авторство
О чём код?
package courseSber.leetCode.math; public class RomanToInt { public static void main(String[] args) { String[] s = {"III", "LVIII", "MCMXCIV"}; for (String str : s) { System.out.println(str + " = " + new RomanToInt().romanToInt(str)); } } private static int getValue(char c) { // свитч быстрее чем мапа return switch (c) { case 'I' -> 1; case 'V' -> 5; case 'X' -> 10; case 'L' -> 50; case 'C' -> 100; case 'D' -> 500; case 'M' -> 1000; default -> 0; }; } public int romanToInt(String s) { int total = 0; int n = s.length(); for (int i = 0; i < n; i++) { int currentVal = getValue(s.charAt(i)); if (i < n - 1 && currentVal < getValue(s.charAt(i + 1))) { total -= currentVal; } else { total += currentVal; } } return total; } }