Concise C++ Solution

• ``````const string HEX = "0123456789abcdef";
class Solution {
public:
string toHex(int num) {
if (num == 0) return "0";
string result;
int count = 0;
while (num && count++ < 8) {
result = HEX[(num & 0xf)] + result;
num >>= 4;
}
return result;
}
};
``````

• Would you mind telling me why you used num & 15 ?

• @OliviaNz It means that he can get half of a byte (range is 0x0 ~ 0xF) in every circulation. An integer number is 4 bytes, so he circulates 8 times.

• @Y_Y Thank you so much for your prompt reply. It was very embarrassed to say that I've no idea what you are talking about. I understand an integer number is 4 bytes. What does that got to do with the rest? If it's too troublesome to explain, would you mind giving me some keywords so I can google myself? Thanks again in advance.

• @OliviaNz
AND operation: http://www.xcprod.com/titan/XCSB-DOC/binary_and.html, the binary of 0xF is 0x1111, so every 4 bits number & 0xF is itself. In other word, An integer number AND with 0xF will get its last 4 bits (0x12345678 & 0x0000000F = 0x00000008).

Owe to my weak english, I will give you an example to explain it.
Suppose hex of the num is 0x12345678.
In first circulation, num &(AND operation) 0xF equals 0x8, then result equals "8". Next execute "num >>= 4", num equals 0x01234567.
In second circulation, num &(AND operation) 0xF equals 0x7, result equals "78" and so on....

• @Y_Y Thank you for your detailed explanation. Sorry, when I said I didn't understand you. That's because I lack of fundamental knowledge. Your English is good. Now I got it. This is a fascinating solution.

• class Solution {
public:
string toHex(int num) {
stringstream ss;
ss<<hex<<num;
string str;
ss>>str;
return str;
}
};

• Do you even need to check the condition 'count++ < 8' ?
num would be 0 anyways after doing 'num >>= 4' eight times if you treat it as an unsigned integer

• This post is deleted!

• HEX[(num & 0xf)] return 0xf for -1 . What is -1 in binary ?. I know MSB will be set but we are ending with only lower 4 bits so it is like 1&0xf ?

• @sumit.083 but its type is not unsigned int. Without the condition `count++ < 8`, it will trap into infinite loop when the input is negative like `-1 (0xffff ffff)`.

• actually, we can use unsigned n instead of num.

``````unsigned n = num;
while(n) {
s = HEX[(num & 0xf)]+ s;
n >>= 4;
}
``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.