Bird
Raised Fist0
DSA Javaprogramming

Roman to Integer Conversion in DSA Java

Choose your learning style10 modes available
Mental Model
Roman numerals are letters that represent values. We add or subtract these values to get the number.
Analogy: Think of reading a price tag where some discounts apply if a smaller number comes before a bigger number, so you subtract instead of add.
R O M A N  N U M E R A L S
I(1) -> V(5) -> X(10) -> L(50) -> C(100) -> D(500) -> M(1000)
Dry Run Walkthrough
Input: Roman numeral: "MCMIV"
Goal: Convert the Roman numeral "MCMIV" to its integer value.
Step 1: Read 'M' (1000), add 1000 to total
total = 1000
Why: Start with the first symbol's value
Step 2: Read 'C' (100), next is 'M' (1000), since 100 < 1000, subtract 100
total = 1000 - 100 = 900
Why: Smaller before bigger means subtract
Step 3: Read 'M' (1000), next is 'I' (1), since 1000 > 1, add 1000
total = 900 + 1000 = 1900
Why: Bigger or equal means add
Step 4: Read 'I' (1), next is 'V' (5), since 1 < 5, subtract 1
total = 1900 - 1 = 1899
Why: Smaller before bigger means subtract
Step 5: Read 'V' (5), no next symbol, add 5
total = 1899 + 5 = 1904
Why: Last symbol always adds
Result:
total = 1904
Annotated Code
DSA Java
import java.util.Map;

public class RomanToInteger {
    private static final Map<Character, Integer> romanMap = Map.of(
        'I', 1,
        'V', 5,
        'X', 10,
        'L', 50,
        'C', 100,
        'D', 500,
        'M', 1000
    );

    public static int romanToInt(String s) {
        int total = 0;
        for (int i = 0; i < s.length(); i++) {
            int currentVal = romanMap.get(s.charAt(i));
            int nextVal = (i + 1 < s.length()) ? romanMap.get(s.charAt(i + 1)) : 0;
            if (currentVal < nextVal) {
                total -= currentVal; // subtract when smaller before bigger
            } else {
                total += currentVal; // add otherwise
            }
        }
        return total;
    }

    public static void main(String[] args) {
        String roman = "MCMIV";
        int result = romanToInt(roman);
        System.out.println(result);
    }
}
int currentVal = romanMap.get(s.charAt(i));
Get value of current Roman symbol
int nextVal = (i + 1 < s.length()) ? romanMap.get(s.charAt(i + 1)) : 0;
Get value of next symbol or 0 if none
if (currentVal < nextVal) {
Check if current is smaller than next to decide subtract
total -= currentVal; // subtract when smaller before bigger
Subtract current value from total
total += currentVal; // add otherwise
Add current value to total
OutputSuccess
1904
Complexity Analysis
Time: O(n) because we scan each Roman character once
Space: O(1) because the map size is fixed and no extra space grows with input
vs Alternative: This is more efficient than checking all substrings or using repeated subtraction which would be slower
Edge Cases
Empty string
Returns 0 because no symbols to convert
DSA Java
int nextVal = (i + 1 < s.length()) ? romanMap.get(s.charAt(i + 1)) : 0;
Single character like 'V'
Returns value of that single symbol (5)
DSA Java
int nextVal = (i + 1 < s.length()) ? romanMap.get(s.charAt(i + 1)) : 0;
All symbols in descending order like 'MDCLXVI'
All values add up normally
DSA Java
if (currentVal < nextVal) {
When to Use This Pattern
When you see a problem asking to convert Roman numerals to numbers, use the subtract-if-smaller-before-bigger pattern to handle special cases.
Common Mistakes
Mistake: Always adding values without checking the next symbol leads to wrong totals for subtractive cases.
Fix: Compare current and next symbol values; subtract current if smaller than next.
Summary
Converts Roman numeral strings to integer values by adding or subtracting symbol values.
Use when you need to interpret Roman numerals as numbers in code.
Remember to subtract when a smaller value comes before a bigger one, otherwise add.

Practice

(1/5)
1. What is the value of the Roman numeral IX when converted to an integer?
easy
A. 6
B. 11
C. 9
D. 19

Solution

  1. Step 1: Understand Roman numeral rules for subtraction

    In Roman numerals, when a smaller numeral appears before a larger one, it is subtracted. Here, I (1) is before X (10), so 1 is subtracted from 10.
  2. Step 2: Calculate the integer value

    10 - 1 = 9.
  3. Final Answer:

    9 -> Option C
  4. Quick Check:

    IX = 9 [OK]
Hint: Subtract when smaller numeral precedes larger one [OK]
Common Mistakes:
  • Adding values instead of subtracting
  • Confusing IX with XI
  • Ignoring subtraction rule
2. Which of the following Java code snippets correctly initializes a map for Roman numeral values?
easy
A. Map map = new HashMap<>(); map.add('I', 1); map.add('V', 5);
B. Map map = Map.of("I", 1, "V", 5, "X", 10);
C. Map map = new Map(); map['I'] = 1; map['V'] = 5;
D. Map map = new HashMap<>(); map.put('I', 1); map.put('V', 5); map.put('X', 10);

Solution

  1. Step 1: Check correct Map initialization syntax in Java

    Java requires using a concrete class like HashMap to create a Map instance. Then, use put() method to add key-value pairs.
  2. Step 2: Verify each option

    Map map = new HashMap<>(); map.put('I', 1); map.put('V', 5); map.put('X', 10); correctly uses new HashMap<>(), then map.put() calls. B uses Map.of with string keys ("I", etc.) causing type mismatch for Map<Character, Integer>. Options C and D use invalid syntax.
  3. Final Answer:

    Map map = new HashMap<>(); map.put('I', 1); map.put('V', 5); map.put('X', 10); -> Option D
  4. Quick Check:

    Use HashMap and put() for map initialization [OK]
Hint: Use HashMap and put() to add entries [OK]
Common Mistakes:
  • Using invalid Map constructor
  • Using map.add() instead of map.put()
  • Trying to assign values with brackets
3. What is the output of the following Java code snippet?
String s = "MCMXCIV";
int result = 0;
Map map = Map.of('I',1,'V',5,'X',10,'L',50,'C',100,'D',500,'M',1000);
for (int i = 0; i < s.length(); i++) {
    int value = map.get(s.charAt(i));
    if (i + 1 < s.length() && value < map.get(s.charAt(i + 1))) {
        result -= value;
    } else {
        result += value;
    }
}
System.out.println(result);
medium
A. 1904
B. 1994
C. 1094
D. 1949

Solution

  1. Step 1: Understand the Roman numeral string and map values

    The string "MCMXCIV" represents a Roman numeral. Map assigns values: M=1000, C=100, X=10, I=1, V=5.
  2. Step 2: Trace the loop and calculate result

    Loop through each character:
    - M(1000), next C(100): 1000 > 100, add 1000
    - C(100), next M(1000): 100 < 1000, subtract 100
    - M(1000), next X(10): 1000 > 10, add 1000
    - X(10), next C(100): 10 < 100, subtract 10
    - C(100), next I(1): 100 > 1, add 100
    - I(1), next V(5): 1 < 5, subtract 1
    - V(5), no next, add 5
    Sum = 1000 - 100 + 1000 - 10 + 100 - 1 + 5 = 1994.
  3. Final Answer:

    1994 -> Option B
  4. Quick Check:

    MCMXCIV = 1994 [OK]
Hint: Subtract if current < next, else add [OK]
Common Mistakes:
  • Adding all values without subtraction
  • Incorrectly subtracting when not needed
  • Misreading character order
4. The following Java method aims to convert a Roman numeral string to an integer but has a bug. What is the bug?
public int romanToInt(String s) {
    Map map = Map.of('I',1,'V',5,'X',10,'L',50,'C',100,'D',500,'M',1000);
    int result = 0;
    for (int i = 0; i < s.length(); i++) {
        int value = map.get(s.charAt(i));
        if (i + 1 < s.length() && value > map.get(s.charAt(i + 1))) {
            result -= value;
        } else {
            result += value;
        }
    }
    return result;
}
medium
A. The comparison operator should be '<' instead of '>' in the if condition.
B. The map initialization is incorrect and causes runtime error.
C. The loop should start from 1 instead of 0.
D. The method does not handle lowercase Roman numerals.

Solution

  1. Step 1: Analyze the if condition logic

    The code subtracts value when current value is greater than next. But Roman numerals subtract when current is less than next.
  2. Step 2: Identify the correct comparison operator

    The condition should be value < map.get(next char) to subtract, not value > next value.
  3. Final Answer:

    The comparison operator should be '<' instead of '>' in the if condition. -> Option A
  4. Quick Check:

    Subtract when current < next [OK]
Hint: Subtract if current numeral is smaller than next [OK]
Common Mistakes:
  • Using wrong comparison operator
  • Ignoring subtraction rule
  • Assuming map initialization error
5. You want to convert a list of Roman numerals ["XL", "IX", "MMXX"] to their integer values using Java. Which approach correctly handles this with minimal code duplication?
hard
A. Write a separate method to convert one Roman numeral to integer, then loop over the list calling this method for each element.
B. Manually convert each Roman numeral in the list with separate code blocks for each string.
C. Use a single loop over the list and convert each character individually without a helper method.
D. Convert only the first Roman numeral and reuse the result for all elements.

Solution

  1. Step 1: Identify the need for reusable code

    Converting Roman numerals requires the same logic for each string. Writing a helper method avoids repeating code.
  2. Step 2: Use a loop to process the list

    Loop through the list and call the helper method for each Roman numeral string to get its integer value.
  3. Final Answer:

    Write a separate method to convert one Roman numeral to integer, then loop over the list calling this method for each element. -> Option A
  4. Quick Check:

    Use helper method + loop for clean code [OK]
Hint: Use helper method and loop to avoid repetition [OK]
Common Mistakes:
  • Repeating conversion code for each string
  • Ignoring code reuse principles
  • Using incorrect logic for all elements
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard