diff options
Diffstat (limited to 'convert_num_hex.py')
-rw-r--r-- | convert_num_hex.py | 29 |
1 files changed, 29 insertions, 0 deletions
diff --git a/convert_num_hex.py b/convert_num_hex.py new file mode 100644 index 0000000..65ca796 --- /dev/null +++ b/convert_num_hex.py @@ -0,0 +1,29 @@ +# 405. Convert a Number to Hexadecimal + +""" +given a 32 bit integer 'num', return a string representing its hexadecimal +representation. for negative integers, two's complement method is used. all +the letters in the answer string should be lowercase characters, nd there not +be any leading zeros in the answer except for the zero itself. note: you are +not allowed to use any built-in library method to directly solve this +problem. +""" + + +class Solution(object): + def toHex(self, num): + """ + :type num: int + :rtype: str + """ + map, ans, num = "0123456789abcdef", "", num & 0xFFFFFFFF + while num: + ans += map[num % 16] + num >>= 4 + return ans[::-1] or "0" + + +if __name__ == "__main__": + obj = Solution() + print(obj.toHex(num=26)) + print(obj.toHex(num=-1)) |