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:

  1. All letters in hexadecimal (a-f) must be in lowercase.
  2. 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.
  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: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 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:LeetCode C++ 450. Delete Node in a BST【二叉搜索树】中等
下一篇:LeetCode C++ 645. Set Mismatch【Hash Table/Bit Manipulation/Math】简单

发表评论

最新留言

能坚持,总会有不一样的收获!
[***.219.124.196]2024年04月24日 15时56分16秒