LeetCode C++ 405. Convert a Number to Hexadecimal【位操作】简单
发布日期:2021-07-01 02:52:53
浏览次数:2
分类:技术文章
本文共 1297 字,大约阅读时间需要 4 分钟。
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:26Output:"1a"
Example 2:
Input:-1Output:"ffffffff"
题意:给定一个整数,编写一个算法将这个数转换为十六进制数。
思路
使用 0xf
获取 num
的低 4
位,对应 1
位十六进制数字。C++的 >>
是算术右移,对正整数右移左边补 0
,对负整数右移左边补 1
,因此位移运算不能保证 num == 0
,需要注意负整数转换的情况:
class Solution { public: string toHex(int num) { string ans; char hex[] = "0123456789abcdef"; bool positive = num >= 0 ? true : false; for (int i = 0; i < 8; ++i) { ans.push_back(hex[num & 0xf]); num >>= 4; if (positive && num == 0) break; //正整数位移可以保证num==0,负整数依赖32位处理 } reverse(ans.begin(), ans.end()); return ans; }};
效率如下:
执行用时:0 ms, 在所有 C++ 提交中击败了100.00% 的用户内存消耗:6 MB, 在所有 C++ 提交中击败了43.53% 的用户
转载地址:https://memcpy0.blog.csdn.net/article/details/108908349 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
网站不错 人气很旺了 加油
[***.192.178.218]2024年04月14日 13时00分18秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
ACM 2014 鞍山区域赛 E - Hatsune Miku (dp)
2019-04-30
反向传播&梯度下降 的直观理解程序(numpy)
2019-04-30
ACM 2017 北京区域赛 J-Pangu and Stones(区间dp)
2019-04-30
java常用类 String面试题
2019-04-30
四线触摸屏原理
2019-04-30
C/C++如何返回一个数组/指针
2019-04-30
腾讯AI语音识别API踩坑记录
2019-04-30
java.net.BindException: 无法指定被请求的地址
2019-05-01
svn服务器安装
2019-05-01
spark 笔记1
2019-05-01
shell dirname basename
2019-05-01
未来已至,5G加持下的云游戏将走向何方?
2019-05-01
计算机网络 —— 网络层 1.
2019-05-01
Android 之 ContentProvider 与 ContentResolver
2019-05-01
【接口自动化】
2019-05-01
推荐一位川大零基础转行 Python 的人生勇士
2019-05-01
Python解惑之:True与False
2019-05-01
你要的微信小程序终于来了
2019-05-01
有了这些 Chrome 插件,效率提升10倍(建议收藏)
2019-05-01
只有1%的程序员搞懂过浮点数陷阱
2019-05-01