---
# System prepended metadata

title: \#405 Convert a Number to Hexadecimal
tags: [leetcode, leetcode-easy]

---

# \#405 Convert a Number to Hexadecimal
## *十進位轉十六進位*
## Log
 - build 20210807 by syhuang

## 參考解
 - 用map存放16進位中0~15代表的數字, 然後跑num, 從右邊開始數每次4位元換算成十六進位對應的數字, 跑到完為止(=0)
 - leetcode submit runtime 70%, memory 30%
```javascript=
var toHex = function(num) {
    if(num==0) return '0';
    let map = '0123456789abcdef';
    let t = num;
    let result = '';
    while(t!=0){
        result = map[(t&15)] + result;
        t>>>=4;
    }
    return result;
    
};
```
## 備註
- ">>>"是帶正負號的位元右移; ">>"則不帶正負號
## 參考
- [參考解](https://leetcode.com/problems/convert-a-number-to-hexadecimal/discuss/89253/Simple-Java-solution-with-comment)
###### tags: `leetcode`, `leetcode-easy`