# 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 `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:
26

Output:
"1a"
``````

Example 2:

``````Input:
-1

Output:
"ffffffff"
``````

``````class Solution {
public:
string toHex(int num) {
string res = "";
vector<string> v{"a","b","c","d","e","f"};
int n = 7;
unsigned int x = num;
if (num < 0) x = UINT_MAX + num + 1;
while (x > 0) {
int t = pow(16, n);
int d = x / t;
if (d >= 10) res += v[d - 10];
else if (d >= 0) res += to_string(d);
x %= t;
--n;
}
while (n-- >= 0) res += to_string(0);
while (!res.empty() && res[0] == '0') res.erase(res.begin());
return res.empty() ? "0" : res;
}
};
``````

``````class Solution {
public:
string toHex(int num) {
string res = "";
for (int i = 0; num && i < 8; ++i) {
int t = num & 0xf;
if (t >= 10) res = char('a' + t - 10) + res;
else res = char('0' + t) + res;
num >>= 4;
}
return res.empty() ? "0" : res;
}
};
``````

``````class Solution {
public:
string toHex(int num) {
string res = "", str = "0123456789abcdef";
int cnt = 0;
while (num != 0 && cnt++ < 8) {
res = str[(num & 0xf)] + res;
num >>= 4;
}
return res.empty() ? "0" : res;
}
};
``````

https://discuss.leetcode.com/topic/60431/concise-c-solution

https://discuss.leetcode.com/topic/60365/simple-java-solution-with-comment

https://discuss.leetcode.com/topic/60412/concise-10-line-c-solution-for-both-positive-and-negative-input

LeetCode All in One 题目讲解汇总(持续更新中…)

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation