|
| 1 | +// https://leetcode.com/problems/integer-to-roman/ |
| 2 | + |
| 3 | +public class IntToRoman { |
| 4 | + /** |
| 5 | + * Convert integer to Roman numeral. We start by holding |
| 6 | + * all the Roman mappings in an array, along with edge cases |
| 7 | + * like 900, 400, 90, 40, 9, 4. We then iterate through the |
| 8 | + * array and keep subtracting the value from the number until |
| 9 | + * we reach 0. |
| 10 | + */ |
| 11 | + public String intToRoman(int num) { |
| 12 | + Roman[] romans = new Roman[] { // Includes 900, 400, 90, 40, 9, 4 |
| 13 | + new Roman(1000, "M"), new Roman(900, "CM"), |
| 14 | + new Roman(500, "D"), new Roman(400, "CD"), |
| 15 | + new Roman(100, "C"), new Roman(90, "XC"), |
| 16 | + new Roman(50, "L"), new Roman(40, "XL"), |
| 17 | + new Roman(10, "X"), new Roman(9, "IX"), |
| 18 | + new Roman(5, "V"), new Roman(4, "IV"), |
| 19 | + new Roman(1, "I") |
| 20 | + }; |
| 21 | + int pointer = 0; |
| 22 | + StringBuilder builder = new StringBuilder(); |
| 23 | + while (num > 0) { |
| 24 | + Roman roman = romans[pointer]; |
| 25 | + while (num >= roman.value()) { |
| 26 | + num -= roman.value(); |
| 27 | + builder.append(roman.code()); |
| 28 | + } |
| 29 | + pointer++; |
| 30 | + } |
| 31 | + return builder.toString(); |
| 32 | + } |
| 33 | + |
| 34 | + private record Roman(int value, String code) { |
| 35 | + } |
| 36 | +} |
0 commit comments