[leetcode]405. Convert a Number to Hexadecimal
Analysis
everyday is the first day of your rest life—— [间歇性迷茫~]
Given an integer, write an algorithm to convert it to hexadecimal.
十进制转十六进制。
note:
& 0xf 相当于对16取余;
>> 4则是右移4位,相当于除以16。
Implement
class Solution {
public:
string toHex(int num) {
if(num == 0)
return "0";
string hex[] = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};
string res = "";
vector<int> index;
int tmp;
while(num){
tmp = num & 0xf;
index.push_back(tmp);
num = (int)((unsigned int) num >> 4);
}
for(int i=index.size()-1; i>=0; i--)
res += hex[index[i]];
return res;
}
};