Sum of Roman Numerals from Decimal Numbers

  • Share this:

Code introduction


Converts two decimal numbers to Roman numerals and calculates their sum.


Technology Stack : Built-in data structures, sorting

Code Type : Function

Code Difficulty : Intermediate


                
                    
def abacuses_sum(num1, num2):
    """
    计算两个十进制数字的罗马数字和。

    :param num1: 第一个十进制数字
    :param num2: 第二个十进制数字
    :return: 两个十进制数字对应的罗马数字之和
    """
    roman_numerals = {
        1: 'I', 4: 'IV', 5: 'V', 9: 'IX', 10: 'X', 40: 'XL', 50: 'L',
        90: 'XC', 100: 'C', 400: 'CD', 500: 'D', 900: 'CM', 1000: 'M'
    }
    
    def int_to_roman(num):
        result = ''
        for value in sorted(roman_numerals.keys(), reverse=True):
            while num >= value:
                result += roman_numerals[value]
                num -= value
        return result

    return int_to_roman(num1) + int_to_roman(num2)