---
title: 'LeetCode 405. Convert a Number to Hexadecimalr'
disqus: hackmd
---
# LeetCode 405. Convert a Number to Hexadecimal
## Description
Given an integer num, return a string representing its hexadecimal representation. For negative integers, two’s complement method is used.
All the letters in the answer string should be lowercase characters, and there should not be any leading zeros in the answer except for the zero itself.
Note: You are not allowed to use any built-in library method to directly solve this problem.
## Example
Input: num = 26
Output: "1a"
Input: num = -1
Output: "ffffffff"
## Constraints
-2^31^ <= x <= 2^31^ - 1
## Answer
此題可以用0xf為mask取出各16進位的數值。先用mask來取出要開多大空間的ans,然後再從最高位一一取4 bit出來轉成16進位即可。
```Cin=
//2022_03_13
char * toHex(int num){
int tmp = 0;
unsigned int mask = 0xf,cnt = 7;
while(cnt>0 && !((num & (mask << (cnt*4))) >> (cnt*4))){cnt--;}
char *ans = (char*)malloc(sizeof(char)*(cnt+2));
ans[cnt+1] = '\0';
for(int i = cnt; i>=0; i--){
tmp = (num & (mask << (i*4))) >> (i*4);
if(tmp>9){ans[cnt - i] = tmp % 10 + 'a';}
else{ans[cnt - i] = tmp + '0';}
}
return ans;
}
```
## Link
https://leetcode.com/problems/convert-a-number-to-hexadecimal/
###### tags: `Leetcode`