# 405.Convert A Number to Hexadecimal

**405.Convert A Number to Hexadecimal**

难度:Easy

> 给定一个整数，编写一个算法将这个数转换为十六进制数。对于负整数，我们通常使用 补码运算 方法。

注意:

十六进制中所有字母(a-f)都必须是小写。 十六进制字符串中不能包含多余的前导零。如果要转化的数为0，那么以单个字符'0'来表示；对于其他情况，十六进制字符串中的第一个字符将不会是0字符。 给定的数确保在32位有符号整数范围内。 不能使用任何由库提供的将数字直接转换或格式化为十六进制的方法。

```
示例 1：

输入:
26

输出:
"1a"
示例 2：

输入:
-1

输出:
"ffffffff"
```

直接每4位判定一下，由于负数右移会补符号位，依然是负数，所以直接转为无符号数即可判断。

```
class Solution {
char u16[16]={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};    
int temp=15;
public:
    string toHex(int num) {
        if(num==0) return "0";
        unsigned int N=num;
        string res;      
        while(N)
        {
            //cout<<num<<endl;
            int index=(N & temp);
            res=u16[index]+res;
            N>>=4;
        }
        return res;

    }
};
```

> 执行用时 :4 ms, 在所有 C++ 提交中击败了87.15%的用户\
> 内存消耗 :8.1 MB, 在所有 C++ 提交中击败了79.86%的用户


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://dfine.gitbook.io/leetcode/405.convert_a_number_to_hexadecimal.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
