Python solution with detailed explanation


  • 0
    G

    Solution

    Integer to Roman https://leetcode.com/problems/integer-to-roman/

    • Maintain a map of key checkpoint integers to their roman numerals.
    • Arrange the checkpoints in decreasing order and keep a pointer to find the checkpoint just smaller than the number. Retrieve its roman string and then subtract the checkpoint from num. Repeat.
    class Solution(object):
        def intToRoman(self, num):
            """
            :type num: int
            :rtype: str
            """
            rmap = {
                        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"
                    }
            seq = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
            so_far, idx = [], 0
            while num > 0:
                if num >= seq[idx]:
                    so_far.append(rmap[seq[idx]])
                    num -= seq[idx]
                else:
                    idx += 1
            return "".join(so_far)
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.