[LeetCode] 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
0
s. 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"
这道题给了我们一个数字,让我们转化为十六进制,抛开题目,我们应该都会把一个十进制数转为十六进制数,比如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
LeetCode All in One 题目讲解汇总(持续更新中...)
[LeetCode] Convert a Number to Hexadecimal 数字转为十六进制的更多相关文章
- Leetcode: Convert a Number to Hexadecimal
Given an integer, write an algorithm to convert it to hexadecimal. For negative integer, two's compl ...
- 405 Convert a Number to Hexadecimal 数字转换为十六进制数
给定一个整数,编写一个算法将这个数转换为十六进制数.对于负整数,我们通常使用 补码运算 方法.注意: 十六进制中所有字母(a-f)都必须是小写. 十六进制字符串中不能包含多余的前导零.如果 ...
- 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 ...
- 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 ...
- [LeetCode] 268. Missing Number ☆(丢失的数字)
转载:http://www.cnblogs.com/grandyang/p/4756677.html Given an array containing n distinct numbers take ...
- 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 ...
- [Swift]LeetCode405. 数字转换为十六进制数 | Convert a Number to Hexadecimal
Given an integer, write an algorithm to convert it to hexadecimal. For negative integer, two’s compl ...
- 【LeetCode】405. Convert a Number to Hexadecimal 解题报告(Java & Python)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 Java解法 Python解法 日期 题目地址:ht ...
- LeetCode算法题-Convert a Number to Hexadecimal(Java实现)
这是悦乐书的第219次更新,第231篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第86题(顺位题号是405).给定一个整数,写一个算法将其转换为十六进制.对于负整数,使 ...
随机推荐
- 未能加载文件或程序集“Owin, Version=1.0.0.0, Culture=neutral, PublicKeyToken=f0ebd12fd5e55cc5”或它的某一个依赖项。系统找不到指定的文件。
在创建ASP.NET MVC项目过程中发生了这个异常 未能加载文件或程序集"Owin, Version=1.0.0.0, Culture=neutral, PublicKeyToken=f0 ...
- winForm连接数据库(sqlserver2005)
帮同学搞个课程设计winform连接sqlserver2005 具体方法: .添加App.config文件 2.在App.config文件中添加节点 <?xml version="1. ...
- JavaWeb_day05cookie_session_HttpSession
本文为博主辛苦总结,希望自己以后返回来看的时候理解更深刻,也希望可以起到帮助初学者的作用. 转载请注明 出自 : luogg的博客园 谢谢配合! 两个会话的技术cookie session 会话概念 ...
- [(ngModel)]的实现原理
讨论[(ngModel)]之前,先讲下属性绑定和事件绑定. 在属性绑定中,值从模型中流动到视图上的目标属性.[],通过把属性名放在方括号中来标记出目标属性.这是从模型到视图的单向数据绑定. 在 ...
- python之最强王者(2)——python基础语法
背景介绍:由于本人一直做java开发,也是从txt开始写hello,world,使用javac命令编译,一直到使用myeclipse,其中的道理和辛酸都懂(请容许我擦干眼角的泪水),所以对于pytho ...
- nginx php-fpm 输出php错误日志
nginx是一个web服务器,因此nginx的access日志只有对访问页面的记录,不会有php 的 error log信息. nginx把对php的请求发给php-fpm fastcgi进程来处理, ...
- MySQL5.7 error log时间显示问题
最近有两三套环境升级到了5.7.16,发现mysql.err中的时间好像有些问题,经查是mysql 5.7后的变更,如下: root@localhost [(none)]>select now( ...
- 用C#从数据库动态生成AdminLTE菜单的一种方法
当前的应用设计风格趋于Flat扁平化,很多基于BootStrap实现了很多UI非常漂亮的管理界面(Bootstrap admin template). 此核心文件开源在Github:https://g ...
- git&&github使用方法总结
vn / git作用:在多人协作开发过程中,我们使用git负责项目源代码的版本管理,所有的开发人员操作的是同一个仓库中的源码 1.创建一个远程的仓库(在gitHub上) 2.创建一个本地的仓库 新建文 ...
- Github装(zao)逼(jia)指(da)南(fa)
Github之于工程师,类似于微博相册之于嫩模,像是个门面. 无论是晋升答辩,还是求职面试,有一个丰富的代码仓库不敢说好处有多大,但总归是有的.并且好处不局限于此,代码开源才会暴露问题才会改正,并且会 ...