|
| 1 | +// https://leetcode.com/problems/integer-to-roman |
| 2 | +// T: O(log n) |
| 3 | +// S: O(log n) |
| 4 | + |
| 5 | +import java.util.Map; |
| 6 | + |
| 7 | +public class IntegerToRoman { |
| 8 | + private final static int ONE = 1; |
| 9 | + private final static int FIVE = 5; |
| 10 | + private final static int TEN = 10; |
| 11 | + |
| 12 | + private final static Map<Integer, String> ONES_PLACE_ROMAN_CHARS = Map.ofEntries( |
| 13 | + Map.entry(ONE, "I"), |
| 14 | + Map.entry(FIVE, "V"), |
| 15 | + Map.entry(TEN, "X") |
| 16 | + ); |
| 17 | + |
| 18 | + private final static Map<Integer, String> TENS_PLACE_ROMAN_CHARS = Map.ofEntries( |
| 19 | + Map.entry(ONE, "X"), |
| 20 | + Map.entry(FIVE, "L"), |
| 21 | + Map.entry(TEN, "C") |
| 22 | + ); |
| 23 | + |
| 24 | + private final static Map<Integer, String> HUNDREDS_PLACE_ROMAN_CHARS = Map.ofEntries( |
| 25 | + Map.entry(ONE, "C"), |
| 26 | + Map.entry(FIVE, "D"), |
| 27 | + Map.entry(TEN, "M") |
| 28 | + ); |
| 29 | + |
| 30 | + public String intToRoman(int num) { |
| 31 | + final StringBuilder result = new StringBuilder(); |
| 32 | + for (int place = 1000 ; num > 0 ; place /= 10) { |
| 33 | + result.append(toRoman(num / place, place)); |
| 34 | + num -= (num / place) * place; |
| 35 | + } |
| 36 | + return result.toString(); |
| 37 | + } |
| 38 | + |
| 39 | + private String toRoman(int digit, int place) { |
| 40 | + return switch (place) { |
| 41 | + case 1 -> toRomanFromPlace(digit, ONES_PLACE_ROMAN_CHARS); |
| 42 | + case 10 -> toRomanFromPlace(digit, TENS_PLACE_ROMAN_CHARS); |
| 43 | + case 100 -> toRomanFromPlace(digit, HUNDREDS_PLACE_ROMAN_CHARS); |
| 44 | + case 1000 -> thousandsPlaceToRoman(digit); |
| 45 | + default -> ""; |
| 46 | + }; |
| 47 | + } |
| 48 | + |
| 49 | + private String toRomanFromPlace(int digit, Map<Integer, String> romanChars) { |
| 50 | + return switch (digit) { |
| 51 | + case 1, 2, 3 -> romanChars.get(ONE).repeat(digit); |
| 52 | + case 4 -> romanChars.get(ONE) + romanChars.get(FIVE); |
| 53 | + case 5, 6, 7, 8 -> romanChars.get(FIVE) + romanChars.get(ONE).repeat(digit - 1); |
| 54 | + case 9 -> romanChars.get(ONE) + romanChars.get(TEN); |
| 55 | + default -> ""; |
| 56 | + }; |
| 57 | + } |
| 58 | + |
| 59 | + private String thousandsPlaceToRoman(int digit) { |
| 60 | + return "M".repeat(digit); |
| 61 | + } |
| 62 | +} |
0 commit comments