Abs.hek
Abs.hek

Reputation: 17

Integer to Roman

The question requires me to return the roman numerals for an integer.

This is my code -

class Solution(object):
    def intToRoman(self, num):
        """
        :type num: int
        :rtype: str
        """
        dict = {
            "I" : 1,
            "IV": 4,
            "V" : 5,
            "IX" : 9,
            "X" : 10, 
            "XL" : 40,
            "L" : 50,
            "XC" : 90,
            "C" : 100, 
            "CD" : 400,
            "D" : 500, 
            "CM" : 900,
            "M" : 1000
        }
        
        returnee = ""
        for k, v in reversed(dict.items()):
            while num > 0: 
                if v <= num:
                    returnee += k
                    num -= v
                else:
                    break
        return returnee

This does not work as the integer nine returns IVIVI instead of IX. Could someone please explain where I am going wrong?

Upvotes: 1

Views: 196

Answers (1)

Kelly Bundy
Kelly Bundy

Reputation: 27629

where I am going wrong?

Using Python 2. Pick Python 3.

(You rely on the order of the dict items, and Python 3 has officially had dicts ordered since 3.7, which is over three years old.)

Upvotes: 3

Related Questions