作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/


题目地址:https://leetcode.com/problems/convert-a-number-to-hexadecimal/

题目描述

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:
26 Output:
"1a"

Example 2:

Input:
-1 Output:
"ffffffff"

题目大意

把一个数字转成16进制,如果这个数字是负数,那么返回它的补码形式。

解题方法

Java解法

只管想法就是把数字/16,然后从数组中取字符组成字符串。但这个只对正数有用,负数没法用。

对负数的处理不好办。刚开始想用Integer.MAX_VALUE减去负数得到整数,再转成16进制,但是,尝试了之后,正数的最大值得符号位是0,因此这个思路不同。

然后就是想到位运算。>>>的作用是无符号右移。每次右移4位就是相当于除以16,然后再把这个结果对16求余,即可。无论正负都可。因为这就是正确的每四位数划分求对应16进制数的方式。

这里有个技巧,就是hexs[(16 + num % 16) % 16],这样做的目的就是使正负数都能统一计算16进制,不会导致数组溢出。

public class Solution {
public String toHex(int num) {
char[] hexs = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
StringBuilder answer = new StringBuilder();
if (num == 0) {
return "0";
}
while (num != 0) {
answer.insert(0, hexs[(16 + num % 16) % 16]);
num = num >>> 4;
} return answer.toString(); }
}

AC: 8 ms

Python解法

二刷的时候使用的是Python解法,这个解法对负数的处理方式是加上2的31次方,这样也就变成了题目要求的补码形式。

class Solution(object):
def toHex(self, num):
"""
:type num: int
:rtype: str
"""
if num == 0:
return "0"
res = ""
if num < 0:
num += 1 << 32
while num != 0:
last = num % 16
if last < 10:
res = str(last) + res
else:
res = chr(last - 10 + ord('a')) + res
num /= 16
return res

日期

2017 年 1 月 14 日
2018 年 11 月 20 日 —— 真是一个好天气

最新文章

  1. html、css基础注意点
  2. WPA: 4-Way Handshake failed - pre-shared key may be incorrect
  3. 学习JAVA 安装
  4. struts2的两个核心配置文件
  5. 使用read write 读写socket
  6. Java 内部类和匿名类 实现JButton动作 ActionListener类
  7. Educational Codeforces Round 1 E. Chocolate Bar 记忆化搜索
  8. MongoDB 日期 插入时少8小时
  9. iOS开发中常用的手势---边缘手势
  10. winform combobox控件绑定 分类: WinForm 2014-04-17 14:34 118人阅读 评论(0) 收藏
  11. [LeetCode OJ] Max Points on a Line—Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
  12. C#图像处理(5):无损保存图片
  13. 企业Centos服务器分区常用方案
  14. socket_sever实现多客户端并发
  15. elk服务器和运维服务器的IPTABLES
  16. 第07章:MongoDB-CRUD操作--文档--创建
  17. 手机e.pageX和e.pageY无效的原因
  18. Java-数组队列
  19. MYSQL创建表的约束条件(可选)
  20. 使用Java、Matlab画多边形闭合折线图

热门文章

  1. R 多图间距调整
  2. 看动画学算法之:二叉搜索树BST
  3. absent, absolute, absorb
  4. 25. Linux下gdb调试
  5. 数据存储SharePreferences详解
  6. Linux学习 - 文件包处理命令
  7. Linux基础命令---get获取ftp文件
  8. Ruby Gems更换淘宝源方法
  9. springboot+vue集成mavon-editor,开发在线文档知识库
  10. 【Java基础】HashMap原理详解