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

Note:

  1. All letters in hexadecimal (a-f) must be in lowercase.
  2. 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.
  3. The given number is guaranteed to fit within the range of a 32-bit signed integer.
  4. You must not use any method provided by the library which converts/formats the number to hex directly.

Example 1:

Input:
26 Output:
"1a"

Example 2:

Input:
-1 Output:
"ffffffff"

Code    T: O(1)

class Solution:
def toHex(self, num):
ans, d = "", {10:'a', 11:'b', 12:'c', 13:'d', 14:'e', 15:'f'}
if num == 0:
return ""
if num < 0:
num = 2**32 + num
while num > 0:
tem, rem = divmod(num, 16)
if rem > 9:
ans += d[rem]
else:
ans += str(rem)
num = tem
return ans[::-1]

最新文章

  1. POJ 1330 Nearest Common Ancestors (最近公共祖先LCA + 详解博客)
  2. web 标准相关
  3. 【转】SQL Server 查询表的记录数(3种方法,推荐第一种)
  4. 完美配置Tomcat的HTTPS
  5. OpenXml操作Word的一些操作总结.无word组件生成word.
  6. BZOJ 1029 建筑抢修
  7. How to Implement the IContextMenu Interface
  8. C#的百度地图开发(二)转换JSON数据为相应的类
  9. PHP memcache实现消息队列实例
  10. 合约广告系统-Hadoop
  11. JSP 学习二
  12. 关于帧动画steps属性的理解
  13. 网站开发进阶(十五)JS基础知识充电站
  14. JVM 启动参数及原理 转
  15. 基于socket实现http请求
  16. Web请求过程
  17. 校验金额、大小写字母、大写字母、合法uri、email
  18. unity3d-游戏实战突出重围,第四天 添加角色
  19. nw.js的localStorage的物理储存位置
  20. 非常酷的CSS3垂直下拉动画菜单

热门文章

  1. E - Cup
  2. Windows 10 Install rabbitmq-server-3.6.9
  3. ASP.NET 前端Ajax获取数据并刷新
  4. tar命令参数详解
  5. [No000016C]做企业分析的三个重要工具
  6. [No0000151]菜鸟理解.NET Framework中的CLI,CLS,CTS,CLR,FCL,BCL
  7. 【作业】DS稀疏矩阵
  8. 用pymysql操作MySQL数据库
  9. [dpdk][kni] dpdk kernel network interface
  10. [development][C] linux 设置线程名称