HomeLeetcode12. Integer to Roman - Leetcode Solutions

12. Integer to Roman – Leetcode Solutions

Description:

Seven different symbols represent Roman numerals with the following values:

SymbolValue
I1
V5
X10
L50
C100
D500
M1000

Roman numerals are formed by appending the conversions of decimal place values from highest to lowest. Converting a decimal place value into a Roman numeral has the following rules:

  • If the value does not start with 4 or 9, select the symbol of the maximal value that can be subtracted from the input, append that symbol to the result, subtract its value, and convert the remainder to a Roman numeral.
  • If the value starts with 4 or 9 use the subtractive form representing one symbol subtracted from the following symbol, for example, 4 is 1 (I) less than 5 (V): IV and 9 is 1 (I) less than 10 (X): IX. Only the following subtractive forms are used: 4 (IV), 9 (IX), 40 (XL), 90 (XC), 400 (CD) and 900 (CM).
  • Only powers of 10 (IXCM) can be appended consecutively at most 3 times to represent multiples of 10. You cannot append 5 (V), 50 (L), or 500 (D) multiple times. If you need to append a symbol 4 times use the subtractive form.

Given an integer, convert it to a Roman numeral.

Examples:

Example 1:

Input: num = 3749

Output: "MMMDCCXLIX"

Explanation:

3000 = MMM as 1000 (M) + 1000 (M) + 1000 (M)
 700 = DCC as 500 (D) + 100 (C) + 100 (C)
  40 = XL as 10 (X) less of 50 (L)
   9 = IX as 1 (I) less of 10 (X)
Note: 49 is not 1 (I) less of 50 (L) because the conversion is based on decimal places

Example 2:

Input: num = 58

Output: "LVIII"

Explanation:

50 = L
 8 = VIII
 
Example 3:

Input: num = 1994

Output: "MCMXCIV"

Explanation:

1000 = M
 900 = CM
  90 = XC
   4 = IV

Solution in Python:

To solve the problem of converting an integer to a Roman numeral in Python, we can use a greedy algorithm. The idea is to repeatedly subtract the largest possible Roman numeral value from the integer until it reaches zero. We’ll use a predefined list of Roman numeral symbols and their corresponding values to guide this process.

Python
class Solution:
    def intToRoman(self, num: int) -> str:
        # Define a list of tuples containing Roman numeral symbols and their corresponding values
        value_symbols = [
            (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')
        ]
        
        # Initialize the result string
        roman = ''
        
        # Loop through each symbol, value pair
        for value, symbol in value_symbols:
            # While the current value can be subtracted from num
            while num >= value:
                # Append the symbol to the result
                roman += symbol
                # Subtract the value from num
                num -= value
        
        return roman

# Example usage
solution = Solution()
print(solution.intToRoman(3749))  # Output: "MMMDCCXLIX"
print(solution.intToRoman(58))    # Output: "LVIII"
print(solution.intToRoman(1994))  # Output: "MCMXCIV"

Explanation:

  1. Define Value-Symbol Pairs:
    • We start by defining a list of tuples value_symbols where each tuple contains a Roman numeral value and its corresponding symbol. The list is ordered from the highest value to the lowest.
  2. Initialize Result String:
    • We initialize an empty string roman which will hold the resultant Roman numeral.
  3. Process Each Value-Symbol Pair:
    • We iterate through each pair (value, symbol) in the value_symbols list.
    • For each pair, we repeatedly subtract the value from num and append the symbol to the roman string until num is smaller than the current value.
    • This ensures that we always use the largest possible symbols first, adhering to the greedy approach.
  4. Return Result:
    • Once we have processed all value-symbol pairs and num has been reduced to zero, the roman string contains the Roman numeral representation of the input integer.

This algorithm ensures that the Roman numeral representation is built correctly and efficiently, adhering to the constraints and rules of Roman numeral formation.

Solution in Javascript:

JavaScript
/**
 * @param {number} num
 * @return {string}
 */
var intToRoman = function(num) {
    // Define a list of tuples containing Roman numeral symbols and their corresponding values
    const 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']
    ];
    
    // Initialize the result string
    let roman = '';
    
    // Loop through each symbol, value pair
    for (let [value, symbol] of valueSymbols) {
        // While the current value can be subtracted from num
        while (num >= value) {
            // Append the symbol to the result
            roman += symbol;
            // Subtract the value from num
            num -= value;
        }
    }
    
    return roman;
};

// Example usage
console.log(intToRoman(3749));  // Output: "MMMDCCXLIX"
console.log(intToRoman(58));    // Output: "LVIII"
console.log(intToRoman(1994));  // Output: "MCMXCIV"

Solution in Java:

Java
class Solution {
    public String intToRoman(int num) {
        // Define a 2D array containing Roman numeral symbols and their corresponding values
        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"}
        };
        
        // Initialize the result string
        StringBuilder roman = new StringBuilder();
        
        // Loop through each symbol, value pair
        for (String[] valueSymbol : valueSymbols) {
            int value = Integer.parseInt(valueSymbol[0]);
            String symbol = valueSymbol[1];
            
            // While the current value can be subtracted from num
            while (num >= value) {
                // Append the symbol to the result
                roman.append(symbol);
                // Subtract the value from num
                num -= value;
            }
        }
        
        return roman.toString();
    }
    
    public static void main(String[] args) {
        Solution solution = new Solution();
        
        // Example usage
        System.out.println(solution.intToRoman(3749));  // Output: "MMMDCCXLIX"
        System.out.println(solution.intToRoman(58));    // Output: "LVIII"
        System.out.println(solution.intToRoman(1994));  // Output: "MCMXCIV"
    }
}

Solution in C#:

C#
public class Solution {
    public string IntToRoman(int num) {
        // Define a 2D array containing Roman numeral symbols and their corresponding values
        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"}
        };
        
        // Initialize the result string
        StringBuilder roman = new StringBuilder();
        
        // Loop through each symbol, value pair
        for (int i = 0; i < valueSymbols.GetLength(0); i++) {
            int value = int.Parse(valueSymbols[i, 0]);
            string symbol = valueSymbols[i, 1];
            
            // While the current value can be subtracted from num
            while (num >= value) {
                // Append the symbol to the result
                roman.Append(symbol);
                // Subtract the value from num
                num -= value;
            }
        }
        
        return roman.ToString();
    }
}

Subscribe
Notify of

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments

Popular