Convert Roman Numeral to Integer (Java)
In this post, we will learn how to convert a Roman numeral string into its integer value using Java. This solution efficiently handles both normal and subtractive cases using a single traversal.
Problem Statement
Given a Roman numeral string, convert it into its corresponding integer value.
Examples:
VIII → 8 IX → 9 LVIII → 58 MCMXCIV → 1994
Approach Used
- Traverse the string from right to left
- Convert each Roman symbol to its integer value
- Add or subtract values based on Roman numeral rules
Java Code Implementation
public class RomanToInteger {
public static void main(String[] args) {
String[] testCases = {
"VIII",
"IX",
"LVIII",
"MCMXCIV",
"XL"
};
for (String roman : testCases) {
System.out.println("Roman: " + roman +
" → Integer: " + romanToInteger(roman));
}
}
private static int romanToInteger(String st) {
int result = 0;
int value = 0;
for (int i = st.length() - 1; i >= 0; i--) {
switch (st.charAt(i)) {
case 'I': value = 1; break;
case 'V': value = 5; break;
case 'X': value = 10; break;
case 'L': value = 50; break;
case 'C': value = 100; break;
case 'D': value = 500; break;
case 'M': value = 1000; break;
}
if (value * 4 < result)
result -= value;
else
result += value;
}
return result;
}
}
Explanation
Right-to-Left Traversal
- Roman numerals follow a subtractive rule (e.g., IV = 4)
- By scanning from right to left, we can decide whether to add or subtract
- If the current value is much smaller than the accumulated result, subtract it
Technique Used: Reverse Traversal + Greedy Decision
Sample Output
Roman: VIII → Integer: 8 Roman: IX → Integer: 9 Roman: LVIII → Integer: 58 Roman: MCMXCIV → Integer: 1994 Roman: XL → Integer: 40
Time & Space Complexity
| Metric | Complexity |
|---|---|
| Time | O(n) |
| Space | O(1) |
Interview Tip
The right-to-left traversal avoids extra data structures and is often preferred in interviews for its simplicity and efficiency.
Want to Go Further?
- Validate invalid Roman numerals
- Convert Integer to Roman
- Solve this using a HashMap approach
👉 Tip: This problem is commonly asked in coding interviews and tests understanding of greedy logic.
Category: Strings
Difficulty: Easy
Techniques: Greedy, Reverse Traversal
No comments:
Post a Comment