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. 读书笔记--SQL必知必会09--汇总数据

    9.1 聚集函数 聚集函数(aggregate function),对某些行运行的函数,计算并返回一个值. 使用聚集函数可以汇总数据而不必将涉及的数据实际检索出来. 可利用标准的算术操作符,实现更高级 ...

  2. HTML5 网络拓扑图性能优化

    HTML5 中的 Canvas 对文本的渲染(fillText,strokeText)性能都不太好,比如设置字体(font).文本旋转(rotation),如果绘制较多的文本时,一些交互操作会手动很大 ...

  3. [WinForm]WinForm跨线程UI操作常用控件类大全

    前言 在C#开发的WinForm窗体程序开发的时候,经常会使用多线程处理一些比较耗时之类的操作.不过会有一个问题:就是涉及到跨线程操作UI元素. 相信才开始接触的人一定会遇上这个问题. 为了解决这个问 ...

  4. 使用图片视频展示插件blueimp Gallery改造网站的视频图片展示

    在很多情况下,我们网站可能会展示我们的产品图片.以及教程视频等内容,结合一个比较好的图片.视频展示插件,能够使得我们的站点更加方便使用,也更加酷炫,在Github上有很多相关的处理插件可以找来使用,有 ...

  5. python之最强王者(3)——变量,条件、循环语句

    1.Python 变量类型 变量存储在内存中的值.这就意味着在创建变量时会在内存中开辟一个空间. 基于变量的数据类型,解释器会分配指定内存,并决定什么数据可以被存储在内存中. 因此,变量可以指定不同的 ...

  6. [转] 评 WOW技能天赋设计

    本文转至:http://bbs.chinaunix.net/thread-1692302-8-1.html(只作转载, 不代表本站和博主同意文中观点或证实文中信息)再比如,传说中的面向对象本该大显神威 ...

  7. JS高程5.引用类型(3)Array类型-检测数组

    1. instanceof操作符(ECMAScript3) 对于一个网页,或者是一个全局作用域而言,使用instanceof操作符来检测数组就可以得到满意的结果. 语法:if(value instan ...

  8. 5分钟让你掌握css3阴影、倒影、渐变小技巧!

    一.开始让大家看一张他们组合的图片再一步一步做: 二.先是建立两个文本不做处理运行如图 三.给第一个div字体加上阴影 text-shadow: 5px 5px 10px red; text-shad ...

  9. windows 7 + virtualbox安装centos+mono+jexus

    1. 下载安装virtualbox和virtualbox extension 2. 创建并安装centos虚拟机 3. 下载并安装libgdiplus,gdi+库 4. 下载并安装Mono 5. 下载 ...

  10. [转]ASP.NET应用程序生命周期趣谈(一)

    这几天一直在看ASP.NET应用程序生命周期,真是太难了,我理解起来费了劲了,但偏偏它又是那么重要,所以我希望能给大家带来一篇容易理解又好用的文章来帮助学习ASP.NET应用程序生命周期.这篇就是了. ...