LeetCode C++ 405. Convert a Number to Hexadecimal【位操作】简单
发布日期:2021-07-01 02:52:53
浏览次数:3
分类:技术文章
本文共 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 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
能坚持,总会有不一样的收获!
[***.219.124.196]2024年04月24日 15时56分16秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
实例属性和类属性
2019-05-02
StringIO和BytesIO
2019-05-02
财务分析与决策:同型分析
2019-05-02
今日整理PDF电子书资料
2019-05-02
【语言-c#】C# 超级整数计算
2019-05-02
【软件-Doxgen】工具:程序代码生成xml文档(doxgen)
2019-05-02
【语言-c#】C# 注释详细介绍说明
2019-05-02
MySQL 内存模型
2019-05-02
node.js 实现一个简单的登录拦截器
2019-05-02
c++抽象类、纯虚函数以及巧用纯虚析构函数实现接口类【转】
2019-05-02
Caffe 安装错误记录及解决办法【转】
2019-05-02
Android用类继承Application的全局变量使用注意
2019-05-02
排序算法之冒泡排序
2019-05-02
算法排序之桶排序
2019-05-02
lambda表达式初探
2019-05-02
C++ Template类模板的特化(3.3节, 3.4节)
2019-05-02