Python; no bit-shifting


  • 0
    Y
    ORD_A = ord('a')
    OFFSET = 16
    
    
    def to_hex(n):
        if not n:
            return '0'
        elif n < 0:
            n = pow(2, 32)+n
        tokens = []
        while n > 0:
            n, rem = divmod(n, OFFSET)
            if rem > 9:
                token = chr(ORD_A + (rem-10))
            else:
                token = str(rem)
            tokens.append(token)
        tokens.reverse()
        return ''.join(tokens)
    

Log in to reply
 

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