【LeetCode】405. Convert a Number to Hexadecimal 解题报告(Java & Python)
2024-08-28 10:25:15
作者: 负雪明烛
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 日 —— 真是一个好天气
最新文章
- html、css基础注意点
- WPA: 4-Way Handshake failed - pre-shared key may be incorrect
- 学习JAVA 安装
- struts2的两个核心配置文件
- 使用read write 读写socket
- Java 内部类和匿名类 实现JButton动作 ActionListener类
- Educational Codeforces Round 1 E. Chocolate Bar 记忆化搜索
- MongoDB 日期 插入时少8小时
- iOS开发中常用的手势---边缘手势
- winform combobox控件绑定 分类: WinForm 2014-04-17 14:34 118人阅读 评论(0) 收藏
- [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.
- C#图像处理(5):无损保存图片
- 企业Centos服务器分区常用方案
- socket_sever实现多客户端并发
- elk服务器和运维服务器的IPTABLES
- 第07章:MongoDB-CRUD操作--文档--创建
- 手机e.pageX和e.pageY无效的原因
- Java-数组队列
- MYSQL创建表的约束条件(可选)
- 使用Java、Matlab画多边形闭合折线图