作者: 负雪明烛
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 日 —— 真是一个好天气

【LeetCode】405. Convert a Number to Hexadecimal 解题报告(Java & Python)的更多相关文章

  1. 38. leetcode 405. Convert a Number to Hexadecimal

    405. Convert a Number to Hexadecimal Given an integer, write an algorithm to convert it to hexadecim ...

  2. LeetCode 405. Convert a Number to Hexadecimal (把一个数转化为16进制)

    Given an integer, write an algorithm to convert it to hexadecimal. For negative integer, two’s compl ...

  3. [leetcode] 405. Convert a Number to Hexadecimal

    https://leetcode.com/contest/6/problems/convert-a-number-to-hexadecimal/ 分析:10进制转换成16进制,不能用库函数,刚开始,我 ...

  4. 【LeetCode】349. Intersection of Two Arrays 解题报告(Java & Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 方法一:Java解法,HashSet 方法二:Pyt ...

  5. 【LeetCode】881. Boats to Save People 解题报告(Python)

    [LeetCode]881. Boats to Save People 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu ...

  6. 【LeetCode】802. Find Eventual Safe States 解题报告(Python)

    [LeetCode]802. Find Eventual Safe States 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemi ...

  7. 【LeetCode】813. Largest Sum of Averages 解题报告(Python)

    [LeetCode]813. Largest Sum of Averages 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemingzhu 个人博 ...

  8. 【LeetCode】692. Top K Frequent Words 解题报告(Python)

    [LeetCode]692. Top K Frequent Words 解题报告(Python) 标签: LeetCode 题目地址:https://leetcode.com/problems/top ...

  9. 【LeetCode】222. Count Complete Tree Nodes 解题报告(Python)

    [LeetCode]222. Count Complete Tree Nodes 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemingzhu 个 ...

随机推荐

  1. 【GS文献】植物全基因组选择育种技术原理与研究进展

    目录 1. 优势杂交育种预测 2. GS育种原理与模型算法 岭回归和LASSO回归 贝叶斯方法 GBLUP和RRBLUP 偏最小二乘法 支持向量机/支持向量回归 其他方法 3. 模型预测能力验证 4. ...

  2. plyr包使用

    #-------------------------------- # plyr包使用# 建议直接保存为R文件到Rstudio中运行 #-------------------------------- ...

  3. R语言与医学统计图形-【29】地图的绘制

    R绘制地图原理: R使用一个个多边形(polygon)来表示每个区域,通过顺次连接GIS数据提供的每个区域多边形的坐标来逐点绘制这些多边形,所以理论上只要得到GIS数据就可绘制相应的地图. 地图绘制说 ...

  4. 查看nginx(Web网页服务器)状态是否正常

    Linux每个应用运行都会产生一个进程,那么我们就可以通过查看Nginx进程是否存在来判断它是否启动. 1.有时想知道nigix是否在正常运行,需要用linux命令查看nginx运行情况.执行命令:p ...

  5. bwa比对软件的使用以及其结果文件(sam)格式说明

    一.bwa比对软件的使用 1.对参考基因组构建索引 bwa index -a bwtsw hg19.fa   #  -a 参数:is[默认] or bwtsw,即bwa构建索引的两种算法,两种算法都是 ...

  6. 33. Implement strStr()

    http://blog.csdn.net/justdoithai/article/details/51287649 理解与分析 Implement strStr() My Submissions Qu ...

  7. java运行报错 has been compiled by a more recent version of the Java Runtime (class file version 55.0), this version of the Java Runtime only recognizes class file versions up to 52.0

    解决方法: 解决办法: 在项目的属性里设置jdk版本,方法是右击项目-->properties-->java compiler --> Enable project specific ...

  8. 数据集成工具—FlinkX

    @ 目录 FlinkX的安装与简单使用 FlinkX的安装 FlinkX的简单使用 读取mysql中student表中数据 FlinkX本地运行 MySQLToHDFS MySQLToHive MyS ...

  9. Gradle—Android配置详解

    参考[1]彻底弄明白Gradle相关配置       [2]Android Studio gradle配置详解

  10. 4.3 rust func closure

    fn add_one_v1 (x: u32) -> u32 { x + 1 } let add_one_v2 = |x: u32| -> u32 { x + 1 }; let add_on ...