diff options
author | Rime <81419447+Emirlol@users.noreply.github.com> | 2024-05-31 20:58:22 +0300 |
---|---|---|
committer | Rime <81419447+Emirlol@users.noreply.github.com> | 2024-06-08 04:13:47 +0300 |
commit | f8a70f9488263cd101d07c1271c68b15c62f959e (patch) | |
tree | 693f1d7209d10c4eebf01b53076eb2abf183fd5d /src/main/java/de/hysky/skyblocker/utils/RomanNumerals.java | |
parent | f056499d12e7e93c922487f859535c2aa502d6ae (diff) | |
download | Skyblocker-f8a70f9488263cd101d07c1271c68b15c62f959e.tar.gz Skyblocker-f8a70f9488263cd101d07c1271c68b15c62f959e.tar.bz2 Skyblocker-f8a70f9488263cd101d07c1271c68b15c62f959e.zip |
Refactor romanToDecimal method to its own class and optimize a few things
Diffstat (limited to 'src/main/java/de/hysky/skyblocker/utils/RomanNumerals.java')
-rw-r--r-- | src/main/java/de/hysky/skyblocker/utils/RomanNumerals.java | 37 |
1 files changed, 37 insertions, 0 deletions
diff --git a/src/main/java/de/hysky/skyblocker/utils/RomanNumerals.java b/src/main/java/de/hysky/skyblocker/utils/RomanNumerals.java new file mode 100644 index 00000000..2ab3c776 --- /dev/null +++ b/src/main/java/de/hysky/skyblocker/utils/RomanNumerals.java @@ -0,0 +1,37 @@ +package de.hysky.skyblocker.utils; + +public class RomanNumerals { + private static int getDecimalValue(char romanChar) { + return switch (romanChar) { + case 'I' -> 1; + case 'V' -> 5; + case 'X' -> 10; + case 'L' -> 50; + case 'C' -> 100; + case 'D' -> 500; + case 'M' -> 1000; + default -> 0; + }; + } + + /** + * Converts a roman numeral to a decimal number. + * + * @param romanNumeral The roman numeral to convert. + * @return The decimal number, or 0 if the roman numeral string is malformed, empty or null. + */ + public static int romanToDecimal(String romanNumeral) { + if (romanNumeral == null || romanNumeral.isEmpty()) return 0; + romanNumeral = romanNumeral.trim().toUpperCase(); + int decimal = 0; + int lastNumber = 0; + for (int i = romanNumeral.length() - 1; i >= 0; i--) { + char ch = romanNumeral.charAt(i); + int number = getDecimalValue(ch); + if (number == 0) return 0; //Malformed roman numeral + decimal = number >= lastNumber ? decimal + number : decimal - number; + lastNumber = number; + } + return decimal; + } +} |