Given an integer, convert it to a roman numeral.
Roman numerals are represented by seven symbols:
| Symbol | Value | |--------|-------| | I | 1 | | V | 5 | | X | 10 | | L | 50 | | C | 100 | | D | 500 | | M | 1000 |
Roman numerals use subtraction notation for 4, 9, 40, 90, 400, and 900:
Example 1:
Input: num = 3
Output: "III"
Example 2:
Input: num = 58
Output: "LVIII"
Explanation: L = 50, V = 5, III = 3
Example 3:
Input: num = 1994
Output: "MCMXCIV"
Explanation: M = 1000, CM = 900, XC = 90, IV = 4
Key Insight: Use the largest possible values first (greedy approach).
Algorithm:
Why include subtraction pairs?
Time Complexity: O(1)
Space Complexity: O(1)
Example: num = 1994
1994 >= 1000 → M, remaining: 994
994 >= 900 → CM, remaining: 94
94 >= 90 → XC, remaining: 4
4 >= 4 → IV, remaining: 0
Result: MCMXCIV
1/**
2 * Integer to Roman
3 * Time: O(1) - fixed iterations
4 * Space: O(1) - fixed result size
5 */
6
7class Solution {
8 public String intToRoman(int num) {
9 // Value-symbol pairs in descending order
10 int[] values = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
11 String[] symbols = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
12
13 StringBuilder result = new StringBuilder();
14
15 for (int i = 0; i < values.length; i++) {
16 // Use the largest value as many times as possible
17 while (num >= values[i]) {
18 result.append(symbols[i]);
19 num -= values[i];
20 }
21 }
22
23 return result.toString();
24 }
25}
26