[LeetCode 405.] Convert a Number to Hexadecimal

LeetCode 405. 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:

  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"

解题思路

一道简单题,给定十进制整数,转换成十六进制表示。整数可为负数。
除了直接调用 I/O库函数 之外,还可以直接使用位运算 —— 注意到十六进制恰好是二进制整数 4bit 一组即可得到。
这些都没有真正涉及取余整除的操作,真正需要逐步计算的是非二的幂次为基数的进制,如 7 进制等。

参考代码

/*
 * @lc app=leetcode id=405 lang=cpp
 *
 * [405] Convert a Number to Hexadecimal
 */

// @lc code=start
class Solution {
public:
/*
    string toHex(int num) {
        char s[20];
        sprintf(s, "%x", num);
        return string(s);
    } // AC
*/
/*
    string toHex(int num) {
        // string s;
        // ostringstream sout(s);
        // sout << hex << num;
        // return s;
        ostringstream sout;
        sout << hex << num;
        return sout.str();
    } // AC
*/
    string toHex(int num) {
        if (num == 0) return "0";
        string res;
        string maps = "0123456789abcdef";
        // while num > 0, for(;num;)
        // while num < 0, for(;i<8;)
        for(int i = 0; (i < 8) && num; i++) {
            res.push_back(maps[num & 0xF]);
            num >>= 4;
        }
        std::reverse(res.begin(), res.end());
        return res;
    } // AC, bitwise op
};
// @lc code=end
posted @ 2021-02-02 11:57  与MPI做斗争  阅读(47)  评论(0编辑  收藏  举报