博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[leetcode: Python]405. Convert a Number to Hexadecimal
阅读量:3557 次
发布时间:2019-05-20

本文共 3989 字,大约阅读时间需要 13 分钟。

Title:

Given an integer, write an algorithm to convert it to hexadecimal. For negative integer, two’s complement method is used.

Note:

All letters in hexadecimal (a-f) must be in lowercase.

The hexadecimal string must not contain extra leading 0s. If the number is zero, it is represented by a single zero character ‘0’; otherwise, the first character in the hexadecimal string will not be the zero character.
The given number is guaranteed to fit within the range of a 32-bit signed integer.
You must not use any method provided by the library which converts/formats the number to hex directly.
Example 1:

Input:26Output:"1a"

Example 2:

Input:-1Output:"ffffffff"

方法一:58ms

class Solution(object):    def toHex(self, num):        """        :type num: int        :rtype: str        """        dict = {
10:'a', 11:'b', 12:'c', 13:'d', 14:'e', 15:'f'} if num == 0: return '0' if num < 0: num += 2**32 s = '' s1 = [] if num > 0 and num < 10: return str(num) elif num >=10 and num < 16: return dict[num] while num >= 16: num, res =divmod(num, 16) s1.append(res) s1.append(num) for i in s1: if i < 10: s = str(i) + s else: s = dict[i] + s return s

方法二:42ms

class Solution(object):    def toHex(self, num):        """        :type num: int        :rtype: str        """        # def get_hex(m, num):        #     res = []        #     while num > 0:        #         res.append(MAP[num % 16])        #         num = num / 16        #     res = ''.join(res[::-1])        #     return res        # def reverse(m, r_m, num):        #     res = []        #     for n in num:        #         res.append(m[15 - r_m[n]])        #     final = ['f'] * 8        #     for i, r in enumerate(res[::-1]):        #         final[7-i] = r        #     return final        # def add_one_on_last(m, r_m, num):        #     c = False        #     if num[7] == 'f':        #         num[7] = '0'        #         c = True        #     else:        #         num[7] = m[r_m[num[7]] + 1]        #     copy_num = num        #     if c:        #         for i, n in enumerate(copy_num[-2::-1]):        #             tmp = r_m[n] + 1        #             if tmp == 16:        #                 num[6-i] = '0'        #             else:        #                 num[6-i] = m[r_m[num[6-i]] + 1]        #                 break        #     return num        # if num == 0:        #     return '0'        # MAP = {
# i: str(i) for i in range(0,10) # } # MAP[10] = 'a' # MAP[11] = 'b' # MAP[12] = 'c' # MAP[13] = 'd' # MAP[14] = 'e' # MAP[15] = 'f' # reverse_map = {v: k for k, v in MAP.items()} # #print(reverse_map) # tmp_num = num if num > 0 else -num # res = get_hex(MAP, tmp_num) # if num < 0: # #print(res) # res = reverse(MAP, reverse_map, res) # #print(res) # res = add_one_on_last(MAP, reverse_map, res) # return ''.join(res) if num==0: return '0' mp = '0123456789abcdef' # like a map ans = '' for i in range(8): n = num % 16 # this means num & 1111b c = mp[n] # get the hex char ans = c + ans num = num >> 4 return ans.lstrip('0') #strip leading zeroes

方法三: 35ms

class Solution(object):    re = {}    def toHex(self, num):        """        :type num: int        :rtype: str        """        if 0 <= num < 10:            return str(num)        if 10 <= num < 16:            return chr(ord('a') + num - 10)        if num not in self.re:            if num < 0:                self.re[num] = self.toHex(2**32+num)            else:                res = num % 16                val = self.toHex(num/16)                self.re[num] = val + self.toHex(res)        return self.re[num]

转载地址:http://sgcrj.baihongyu.com/

你可能感兴趣的文章
前端网页学习7(css背景属性)
查看>>
前端网页学习8(css三大特性:层叠性,继承性,优先级)
查看>>
前端网页学习9(css盒子)
查看>>
python学习8(列表)
查看>>
JavaScript学习(new1)
查看>>
http GET 和 POST 请求的优缺点、区别以及误区
查看>>
JVM的4种垃圾回收算法、垃圾回收机制
查看>>
什么是分布式事务
查看>>
常用的分布式事务解决方案
查看>>
设计模式:单例模式 (关于饿汉式和懒汉式)
查看>>
一致性Hash算法
查看>>
更新Navicat Premium 后打开数据库出现1146 - Table 'performance_schema.session_variables' doesn't exist
查看>>
安装rabbitmq时踩的坑
查看>>
2021-06-09数据库添加多条数据
查看>>
简单的JAVA小作品
查看>>
CMake下载
查看>>
未调用fflush产生的图片文件无法打开问题
查看>>
SQL 约束(二)
查看>>
SQL ALTER用法(三)
查看>>
SQL where子句及查询条件语句(六)
查看>>