Skip to content

Latest commit

 

History

History
32 lines (22 loc) · 605 Bytes

405.md

File metadata and controls

32 lines (22 loc) · 605 Bytes

405 Convert a Number to Hexadecimal

Description

link


Solution

  • Code

Code

O(n)

class Solution:
    def toHex(self, num: int) -> str:
        int2char = {15:'f', 14:'e', 13:'d', 12:'c', 11:'b', 10:'a'}
        num = 2 ** 32 + num if num < 0 else num
        res = []
        while num >= 16:
            bit = num & 15
            num = num >> 4
            res.append(bit)
        res.append(num)
            
        return ''.join([str(x) if x < 10 else int2char[x] for x in res[::-1]])