O(1) hash table method in Python with defined data structure


  • 0
    M
            matrix = {
                1000:{
                    1: 'M',
                    2: 'MM',
                    3: 'MMM'
                },
                100:{
                    1: 'C',
                    2: 'CC',
                    3: 'CCC',
                    4: 'CD',
                    5: 'D',
                    6: 'DC',
                    7: 'DCC',
                    8: 'DCCC',
                    9: 'CM'
                },
                10:{
                    1: 'X',
                    2: 'XX',
                    3: 'XXX',
                    4: 'XL',
                    5: 'L',
                    6: 'LX',
                    7: 'LXX',
                    8: 'LXXX',
                    9: 'XC'
                },
                1:{
                    1: 'I',
                    2: 'II',
                    3: 'III',
                    4: 'IV',
                    5: 'V',
                    6: 'VI',
                    7: 'VII',
                    8: 'VIII',
                    9: 'IX'
                }
            } # matrix ends
            rm = ''
            for i in [1000, 100, 10, 1]:
                a = num / i
                b = num % i
    
                if a != 0:
                    rm += matrix[i][a]
    
                num = b
            return rm
    

Log in to reply
 

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