Home  Dsa   Roman to in ...

Roman to Integer problem and solution in Java and Python

Let’s cover both directions — Roman → Integer and Integer → Roman — with full intuition, Java + Python code, and visual understanding.


🧩 1️⃣ Problem: Roman to Integer

Question

Given a string representing a Roman numeral, convert it to an integer.


Roman Numeral Basics

SymbolValue
I1
V5
X10
L50
C100
D500
M1000

But there are subtractive cases:


Example

Input: "MCMXCIV"
Output: 1994
Explanation:
M (1000) + CM (900) + XC (90) + IV (4)
= 1994

Approach


Java Solution

import java.util.*;

class Solution {
    public int romanToInt(String s) {
        Map<Character, Integer> map = new HashMap<>();
        map.put('I', 1);
        map.put('V', 5);
        map.put('X', 10);
        map.put('L', 50);
        map.put('C', 100);
        map.put('D', 500);
        map.put('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;
    }
}

Python Solution

def romanToInt(s: str) -> int:
    roman = {'I': 1, 'V': 5, 'X': 10, 'L': 50,
             'C': 100, 'D': 500, 'M': 1000}
    total = 0

    for i in range(len(s)):
        if i + 1 < len(s) and roman[s[i]] < roman[s[i + 1]]:
            total -= roman[s[i]]
        else:
            total += roman[s[i]]
    return total

🧠 To Explain to a Kid

Think of Roman numbers as stickers with values. If a smaller sticker (I) comes before a bigger one (V), you’re taking away one sticker’s value — that’s why IV = 4.


⚙️ Complexity

TypeTimeSpace
Roman → IntegerO(n)O(1)


🧩 2️⃣ Problem: Integer to Roman

Question

Given an integer (1 ≤ num ≤ 3999), convert it to a Roman numeral.


Idea

We can map integer values to Roman numerals from largest to smallest, and greedily subtract.

ValueSymbol
1000M
900CM
500D
400CD
100C
90XC
50L
40XL
10X
9IX
5V
4IV
1I

Example

Input: 1994
Output: "MCMXCIV"
Explanation:
1000 (M) + 900 (CM) + 90 (XC) + 4 (IV)

Java Solution

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 sb = new StringBuilder();

        for (int i = 0; i < values.length; i++) {
            while (num >= values[i]) {
                num -= values[i];
                sb.append(symbols[i]);
            }
        }
        return sb.toString();
    }
}

Python Solution

def intToRoman(num: int) -> str:
    val = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
    syms = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"]
    
    roman = []
    for i in range(len(val)):
        while num >= val[i]:
            num -= val[i]
            roman.append(syms[i])
    return ''.join(roman)

🧠 To Explain to a Kid

Imagine you’re making change for money. You always give the largest coin first — just like you write M (1000) before C (100), etc.

So for 1994:


⚙️ Complexity

TypeTimeSpace
Integer → RomanO(1)O(1)
Because Roman numerals have a fixed set of symbols, and the loop runs a constant number of times.

🌍 Real-World Use

Roman numerals are still used in:


Published on: Oct 11, 2025, 10:50 PM  
 

Comments

Add your comment