Two short Python beats 80%


  • 1

    Use less mem:

    class Solution(object):
        def intToRoman(self, num):
            symbols = ["M", "D", "C", "L", "X", "V", "I"]
            ret, div, symPos = "", 1000, 0
            while num > 0:
                v = num / div
                if v <= 3:
                    ret += v * symbols[symPos]
                elif v == 4:
                    ret += symbols[symPos] + symbols[symPos - 1]
                elif v >= 5 and v < 9:
                    ret += symbols[symPos - 1] + (v - 5) * symbols[symPos]
                elif v == 9:
                    ret += symbols[symPos] + symbols[symPos - 2]
                num = num % div
                div /= 10
                symPos += 2
            return ret
    

    The other solution using table:

    class Solution(object):
        def intToRoman(self, num):
            symbols = ["M", "D", "C", "L", "X", "V", "I"]
            M = ["", "M", "MM", "MMM"]
            C = ["", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"]
            X = ["", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"]
            I = ["", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"]
            return M[num/1000] + C[(num%1000)/100] + X[(num%100)/10] + I[num%10]

Log in to reply
 

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