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"

这道题给了我们一个数字,让我们转化为十六进制,抛开题目,我们应该都会把一个十进制数转为十六进制数,比如50,转为十六进制数,我们先对50除以16,商3余2,那么转为十六进制数就是32。所以我们就按照这个思路来写代码,由于输入数字的大小限制为int型,我们对于负数的处理方法是用其补码来运算,那么数字范围就是0到UINT_MAX,即为16^8-1,那么最高位就是16^7,我们首先除以这个数字,如果商大于等于10,我们用字母代替,否则就是用数字代替,然后对其余数进行同样的处理,一直到当前数字为0停止,最后我们还要补齐末尾的0,方法根据n的值,比-1大多少就补多少个0。由于题目中说明了最高位不能有多余的0,所以我们将起始0移除,如果res为空了,我们就返回0即可,参见代码如下:

解法一:

class Solution {
public:
string toHex(int num) {
string res = "";
vector<string> v{"a","b","c","d","e","f"};
int n = ;
unsigned int x = num;
if (num < ) x = UINT_MAX + num + ;
while (x > ) {
int t = pow(, n);
int d = x / t;
if (d >= ) res += v[d - ];
else if (d >= ) res += to_string(d);
x %= t;
--n;
}
while (n-- >= ) res += to_string();
while (!res.empty() && res[] == '') res.erase(res.begin());
return res.empty() ? "" : res;
}
};

上述方法稍稍复杂一些,我们来看一种更简洁的方法,我们采取位操作的思路,每次取出最右边四位,如果其大于等于10,找到对应的字母加入结果,反之则将对应的数字加入结果,然后num像右平移四位,循环停止的条件是num为0,或者是已经循环了7次,参见代码如下:

解法二:

class Solution {
public:
string toHex(int num) {
string res = "";
for (int i = ; num && i < ; ++i) {
int t = num & 0xf;
if (t >= ) res = char('a' + t - ) + res;
else res = char('' + t) + res;
num >>= ;
}
return res.empty() ? "" : res;
}
};

下面这种写法更加简洁一些,虽然思路跟解法二并没有什么区别,但是我们把要转换的十六进制的数字字母都放在一个字符串中,按位置直接取就可以了,参见代码如下:

解法三:

class Solution {
public:
string toHex(int num) {
string res = "", str = "0123456789abcdef";
int cnt = ;
while (num != && cnt++ < ) {
res = str[(num & 0xf)] + res;
num >>= ;
}
return res.empty() ? "" : res;
}
};

参考资料:

https://discuss.leetcode.com/topic/60431/concise-c-solution

https://discuss.leetcode.com/topic/60365/simple-java-solution-with-comment

https://discuss.leetcode.com/topic/60412/concise-10-line-c-solution-for-both-positive-and-negative-input

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] Convert a Number to Hexadecimal 数字转为十六进制的更多相关文章

  1. Leetcode: Convert a Number to Hexadecimal

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

  2. 405 Convert a Number to Hexadecimal 数字转换为十六进制数

    给定一个整数,编写一个算法将这个数转换为十六进制数.对于负整数,我们通常使用 补码运算 方法.注意:    十六进制中所有字母(a-f)都必须是小写.    十六进制字符串中不能包含多余的前导零.如果 ...

  3. 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 ...

  4. LeetCode_405. Convert a Number to Hexadecimal

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

  5. [LeetCode] 268. Missing Number ☆(丢失的数字)

    转载:http://www.cnblogs.com/grandyang/p/4756677.html Given an array containing n distinct numbers take ...

  6. 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 ...

  7. [Swift]LeetCode405. 数字转换为十六进制数 | Convert a Number to Hexadecimal

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

  8. 【LeetCode】405. Convert a Number to Hexadecimal 解题报告(Java & Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 Java解法 Python解法 日期 题目地址:ht ...

  9. LeetCode算法题-Convert a Number to Hexadecimal(Java实现)

    这是悦乐书的第219次更新,第231篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第86题(顺位题号是405).给定一个整数,写一个算法将其转换为十六进制.对于负整数,使 ...

随机推荐

  1. C#——this关键字(1)

    //我的C#是跟着猛哥(刘铁猛)(算是我的正式老师)<C#语言入门详解>学习的,微信上猛哥也给我讲解了一些不懂得地方,对于我来说简直是一笔巨额财富,难得良师! 在学习C#的时候,老师讲的示 ...

  2. jQuery+CSS3文字跑马灯特效

    jQuery+CSS3文字跑马灯特效是一款将跑马灯背景制作为3D立方体效果,文字在上面移动时,就像是文字投影到墙壁上,在转角出会改变运动方向. 效果展示 http://hovertree.com/te ...

  3. Quartz —— Spring 环境下的使用

    一.在 Spring 环境下 Quartz 的使用超级简单. 二.具体使用 1.添加对应的 spring-quartz 的配置文件. 2.新建要执行定时任务的目标类和目标方法,不需要继承 Job 接口 ...

  4. AJAX表单提交以及数据接收

    ajax是一种传输方式,数据不是提交给ajax,而是 数据 由 ajax提交到后台(并不刷新页面) 要实现一个简单的ajax请求,要这3样东西,一个html页,一段js代码,一个可以响应请求的后台 这 ...

  5. windows上如何搭建Git Server

    Git在版本控制方面,相比与SVN有更多的灵活性,对于开源的项目,我们可以托管到Github上面,非常方便,但是闭源的项目就会收取昂贵的费用.那么私有项目,如何用Git进行代码版本控制呢?我们可以自己 ...

  6. 4款最具影响力的自助式BI工具

    数据为王的时代,人人都需要掌握一些数据分析技能.不懂SQL,不懂数据库,Excel不精通,VBA不敢碰,这些都是横亘在面前的一道坎. 然而,企业数据分析日益上涨,数据人才供不应求,为了降低入门门槛,近 ...

  7. yii2实战教程之新手入门指南-简单博客管理系统

    作者:白狼 出处:http://www.manks.top/document/easy_blog_manage_system.html 本文版权归作者,欢迎转载,但未经作者同意必须保留此段声明,且在文 ...

  8. SQL删除语句同时向备份表插入数据

    从这里摘抄下来的,觉得很不错,http://www.cnblogs.com/ljhdo/p/5792886.html#3503524 ,以后就用这种方式删除,再也不用担心删除错数据啦!!!

  9. Linux设备树语法详解

    概念 Linux内核从3.x开始引入设备树的概念,用于实现驱动代码与设备信息相分离.在设备树出现以前,所有关于设备的具体信息都要写在驱动里,一旦外围设备变化,驱动代码就要重写.引入了设备树之后,驱动代 ...

  10. Redis 与 数据库处理数据的两种模式

    Redis 是一个高性能的key-value数据库. redis的出现,很大程度补偿了memcached这类key-value存储的不足,在部 分场合可以对关系数据库起到很好的补充作用.它提供了Pyt ...