Basic program to convert integer to Roman numerals?

后端 未结 24 1091
孤独总比滥情好
孤独总比滥情好 2020-11-30 11:52

I\'m trying to write a code that converts a user-inputted integer into its Roman numeral equivalent. What I have so far is:

The point of the generate_

24条回答
  •  有刺的猬
    2020-11-30 12:17

    I referred to this url for online decimal to roman conversion. If we extend the range of decimals up to 3,999,999 the script given by @Manhattan will not work. Here is the the correct script up to the range of 3,999,999.

    def int_to_roman(num):
        _values = [
            1000000, 900000, 500000, 400000, 100000, 90000, 50000, 40000, 10000, 9000, 5000, 4000, 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
    
        _strings = [
            'M', 'C', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"]
    
        result = ""
        decimal = num
    
        while decimal > 0:
            for i in range(len(_values)):
                if decimal >= _values[i]:
                    if _values[i] > 1000:
                        result += u'\u0304'.join(list(_strings[i])) + u'\u0304'
                    else:
                        result += _strings[i]
                    decimal -= _values[i]
                    break
        return result
    

    The unicode character u'\0304' prints the overline char; e.g.

    Sample Output:

提交回复
热议问题