A function to convert a number to roman numerals Examples: num = 3 -> `III`, num = 58 --> `LVIII` @param num @return String
(int num)
| 15 | */ |
| 16 | |
| 17 | public static String intToRoman(int num) { |
| 18 | Map<Integer, String> map = new HashMap<Integer, String>(); |
| 19 | map.put(1, "I"); |
| 20 | map.put(4, "IV"); |
| 21 | map.put(5, "V"); |
| 22 | map.put(9, "IX"); |
| 23 | map.put(10, "X"); |
| 24 | map.put(40, "XL"); |
| 25 | map.put(50, "L"); |
| 26 | map.put(90, "XC"); |
| 27 | map.put(100, "C"); |
| 28 | map.put(400, "CD"); |
| 29 | map.put(500, "D"); |
| 30 | map.put(900, "CM"); |
| 31 | map.put(1000, "M"); |
| 32 | |
| 33 | List<Integer> mapKeys = Arrays.asList(1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1); |
| 34 | int remainder = num; |
| 35 | StringBuilder result = new StringBuilder(""); |
| 36 | int mapKeysIndex = 0; |
| 37 | |
| 38 | while (remainder != 0) { |
| 39 | int currentComparison = mapKeys.get(mapKeysIndex); |
| 40 | if (remainder < currentComparison) { |
| 41 | mapKeysIndex++; |
| 42 | continue; |
| 43 | } |
| 44 | |
| 45 | result.append(map.get(currentComparison)); |
| 46 | remainder = remainder - currentComparison; |
| 47 | } |
| 48 | |
| 49 | return result.toString(); |
| 50 | } |
| 51 | |
| 52 | public static void main(String[] args) { |
| 53 | Scanner sc = new Scanner(System.in); |