Integer to Roman - LeetCode Solution in C++, Java, Python

1. Introduction

The "Integer to Roman" problem involves converting a given integer to a Roman numeral. Roman numerals use seven symbols (I, V, X, L, C, D, M) and are written largest to smallest from left to right, with special rules for subtraction in certain instances.

2. Problem

Given an integer, convert it to a Roman numeral. Roman numerals are represented by combinations of letters from the Latin alphabet (I, V, X, L, C, D, M) and follow specific subtraction rules for certain pairs.

3. Solution in C++

string intToRoman(int num) {
    vector<pair<int, string>> valueSymbols = {{1000, "M"}, {900, "CM"}, {500, "D"}, {400, "CD"}, {100, "C"}, {90, "XC"}, {50, "L"}, {40, "XL"}, {10, "X"}, {9, "IX"}, {5, "V"}, {4, "IV"}, {1, "I"}};
    string roman;
    for (const auto &valueSymbol : valueSymbols) {
        while (num >= valueSymbol.first) {
            num -= valueSymbol.first;
            roman += valueSymbol.second;
        }
    }
    return roman;
}

Explanation:

1. Create a vector of pairs associating integers with their Roman numeral representations.

2. Iterate through this vector, subtracting the value from num and appending the corresponding Roman numeral to the string roman.

3. Continue this process until num is reduced to zero.

4. The final string roman is the Roman numeral representation of the integer.

4. Solution in Java

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 && num > 0; i++) {
        while (num >= values[i]) {
            num -= values[i];
            roman.append(symbols[i]);
        }
    }
    return roman.toString();
}

Explanation:

1. Define arrays values and symbols containing the integer values and their respective Roman numeral symbols.

2. Use a StringBuilder to build the Roman numeral.

3. Loop through values, subtracting from num and appending the corresponding symbol to the StringBuilder.

4. The final result is the Roman numeral representation of the integer.

5. Solution in Python

def intToRoman(num):
    valueSymbols = [(1000, "M"), (900, "CM"), (500, "D"), (400, "CD"), (100, "C"), (90, "XC"), (50, "L"), (40, "XL"), (10, "X"), (9, "IX"), (5, "V"), (4, "IV"), (1, "I")]
    roman = ""
    for value, symbol in valueSymbols:
        while num >= value:
            num -= value
            roman += symbol
    return roman

Explanation:

1. Create a list valueSymbols pairing integer values with their Roman numeral symbols.

2. Initialize an empty string roman for the Roman numeral.

3. Iterate through the valueSymbols, subtracting the value from num and appending the symbol to roman.

4. Repeat the process until num becomes zero.

5. Return roman as the Roman numeral equivalent of the integer.


Comments