1-liner in Python

  • 13
    class Solution(object):
        def toHex(self, num):
            return   ''.join(
                            '0123456789abcdef'[(num >> 4 * i) & 15] 
                            for i in range(8)
                            )[::-1].lstrip('0') or '0'

  • 1

    *cough* res *cough* :-P

    I'll think about more, but for now I'll mention that '0123456789abcdef' is shorter than (string.digits + string.ascii_letters) and 15 is shorter than 0b1111.

  • 0

    @StefanPochmann Thanks Stefan.

  • 4

    Here's a short one with the extra parameter trick you probably tried:

    def toHex(self, num, h=''):
        return (not num or h[7:]) and h or self.toHex(num / 16, '0123456789abcdef'[num % 16] + h)

Log in to reply

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