# C++ 0ms

• ``````class Solution {
public:
string toHex(int num) {
int count = 0;
if(!num) return "0";
string result;
while (num && count < 8)
{
int temp = num & 15;
if (temp<10)    result.push_back('0'+ temp);
else result.push_back('a'+temp-10);
num = num >> 4;
count++;
}
reverse(result.begin(),result.end());
return result;
}
};
``````

• Using & and >> is quicker than using % and /.
Thanks~

• this does not deal with negative integer, right?

• @jyty All the number in memory are stored in Two's complement. So it's OK to fit both positive and negative number.

• @yangjiannr it's a smart way to solve this problem.
And I do this in a rude way.

class Solution {
public:
string positiveToHex(int num){
string result;
int quot = 0, remain = 0;
quot = num/16;
remain = num%16;
if(num < 16) return result+digit[num];
num = quot;
result.push_back(digit[remain]);
while(num >= 16)
{
quot = num/16;
remain = num%16;
result.push_back(digit[remain]);
num = quot;
}

``````    result.push_back(digit[num]);
reverse(result.begin(), result.end());
return result;

}
string toHex(int num) {
if(num >= 0)
return positiveToHex(num);
else{
string tmp = positiveToHex(INT_MAX+num+1);
cout << INT_MAX;
cout << tmp;
for(int i = tmp.size(); i < 8; i++)
{
tmp.insert(0,"0");
}
cout << tmp;
int index = tmp[0] - '0';
tmp[0] = digit[index+8];
return tmp;
}

}
``````

private:
vector<char> digit = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
};

• list item

• said in C++ 0ms:

while (num && count < 8)

In the while condition "while (num && count < 8)", why do we need count < 8? (num != 0) is not enough?

• @queenafly I was confused as well but I just figure it out. The first thing is that the given number if a 32-bit decimal integer, which can be represented as an 8-bit Hexadecimal integer. The magic here is the mechanism of two's complement for -1: no matter how many bits you shift -1(which is 0xffffffff), it is still -1 cause we will round down the divided number. Remember, if you right shift -1 for 1 bit, it is equivalent to divide -1 by 2, which is -0.5 and it is rounded to -1 again. BOOM!

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