LeetCode 12: Integer to Roman Solution
Master LeetCode problem 12 (Integer to Roman), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
12. Integer to Roman
Problem Explanation
Explanation
To solve this problem, we can iterate over the given integer while reducing it based on the highest Roman numeral value possible at each step. We can create a mapping of Roman numeral symbols to their decimal values and use this mapping to construct the Roman numeral representation of the input integer.
- Create a mapping of Roman numeral symbols to their decimal values.
- Iterate over the mapping in descending order of decimal values.
- At each step, check if the current decimal value can be subtracted from the input integer.
- If yes, append the corresponding Roman numeral symbol to the result and subtract its decimal value from the input.
- Repeat until the input integer becomes 0.
Time Complexity
The time complexity of this approach is O(1) since the maximum input constraint is 3999, which requires a constant number of operations.
Space Complexity
The space complexity is O(1) as we are using a fixed amount of space for the mapping and the result string.
Solution Code
class Solution {
public String intToRoman(int num) {
int[] values = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
String[] symbols = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
StringBuilder roman = new StringBuilder();
for (int i = 0; i < values.length; i++) {
while (num >= values[i]) {
roman.append(symbols[i]);
num -= values[i];
}
}
return roman.toString();
}
}
Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 12 (Integer to Roman)?
This page provides optimized solutions for LeetCode problem 12 (Integer to Roman) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 12 (Integer to Roman)?
The time complexity for LeetCode 12 (Integer to Roman) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 12 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 12 in Java, C++, or Python.