作者: 负雪明烛
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. shell 脚本自动插入文件头

    vim编辑shell脚本自动插入文件头部信息,将下面的代码写入home目录xia .vimrc 文件即可. shell 文件头: 1 autocmd BufNewFile *.sh exec &quo ...

  2. 在R语言中使用Stringr进行字符串操作

    今天来学习下R中字符串处理操作,主要是stringr包中的字符串处理函数的用法. 先导入stringr包,library(stringr),require(stringr),或者stringr::函数 ...

  3. OOM机制

    Linux内核根据应用程序的要求分配内存,通常来说应用程序分配了内存但是并没有实际全部使用,为了提高性能,这部分没用的内存可以留作它用,这部分内存是属于每个进程的,内核直接回收利用的话比较麻烦,所以内 ...

  4. Python基础之流程控制while循环

    目录 1. 语法 2. while+break 3. while+continue 4. while+else 1. 语法 最简单的while循环如下: ''' while <条件>: & ...

  5. python2 第二天

    requests库 编码和解码 输入和输出,在Python中,为了更好的调试和输出,我们需要对字符串进⾏格式化的输出,⽐如我们定义了姓名和年龄,但是我 们需要输出完整的信息,那么就涉及到字符串格式化的 ...

  6. python-3.x-生成器使用

    生成器函数代码: 1 def gen(n): 2 i = 1; 3 sum = 0; 4 while i <= n: 5 ''' 6 方法体1 -- sum求和是1到9的和 7 yield su ...

  7. LeetCode一维数组的动态和

    一维数组的动态和 题目描述 给你一个数组 nums.数组「动态和」的计算公式为:runningSum[i] = sum(nums[0]...nums[i]). 请返回 nums 的动态和. 示例 1: ...

  8. 22 SHELL 获取当前路径

    常见的一种误区,是使用 pwd 命令,该命令的作用是"print name of current/working directory",这才是此命令的真实含义,当前的工作目录,这里 ...

  9. Spark中的分区方法详解

    转自:https://blog.csdn.net/dmy1115143060/article/details/82620715 一.Spark数据分区方式简要 在Spark中,RDD(Resilien ...

  10. Spark(十一)【SparkSQL的基本使用】

    目录 一. SparkSQL简介 二. 数据模型 三. SparkSQL核心编程 1. IDEA开发SparkSQL 2. SparkSession 创建 关闭 获取SparkContext 3. D ...