diff options
author | Jack Sangdahl <[email protected]> | 2025-03-15 02:05:58 -0600 |
---|---|---|
committer | Jack Sangdahl <[email protected]> | 2025-03-15 02:05:58 -0600 |
commit | 5e923e65f2bef08dd917ca1cf9581a7a60bab8c9 (patch) | |
tree | 8b7f0c5080c8c093839c1e9b35d808287e8e7f17 /convert_num_hex.py | |
parent | 95c460fc44a3ccee0b366b67cf47df0576f2fa32 (diff) | |
download | leetcode-5e923e65f2bef08dd917ca1cf9581a7a60bab8c9.tar.gz leetcode-5e923e65f2bef08dd917ca1cf9581a7a60bab8c9.zip |
405. convert a number to hexadecimal
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)) |