# Leetcode :: Convert a Number to Hexadecimal

wisepineยท2021๋ 6์ 27์ผ
0

## ์๊ณ ๋ฆฌ์ฆ

๋ชฉ๋ก ๋ณด๊ธฐ
107/122

### Problem

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.

### Guess

• ํ ๋ง๋๋ก ์ซ์๋ฅผ 16์ง์๋ก ๋ณํํ๋, ์์๋ 2์ ๋ณด์๋ฒ์ ๋ฐ๋ผ๋ผ.

• 2์ ๋ณด์๋ก ์ด์งํํด์ ํํํ๋ ๋ถ๋ถ์ ์ปดํจํฐ๊ฐ ์๋์ผ๋ก ํด์ค๋ค..

• ์ฐ๋ฆฌ๊ฐ ๊ณ ๋ คํ ๊ฑด, 16์ง์๋ก ๋๋  ํํํ๋ ๋ถ๋ถ๋ง ํ๋ฉด ๋๋ค.

### Solution

def toHex(num: int):
if num==0: return '0'
mp = '0123456789abcdef'  # like a map
ans = ''

for i in range(8):
n = num & 15
ans = mp[n] + ans
num >>= 4

return ans.lstrip('0')

• ์ด์ง์ 4์๋ฆฌ(16์ฉ) ๋๋ ์ 16์ง์๋ฒ์ผ๋ก ๋ณํํด์ผํ๋ฏ๋ก

• 1111b, ์ฆ 15์ AND ์ฐ์ฐํ์ฌ ์ชผ๊ฐ์ค๋ค. (n % 16์ ๊ฐ๋ค.)

• ๊ทธ ๋ค์ ์ค๋ฅธ์ชฝ์ผ๋ก shiftํ์ฌ ๋ณํํ ๋ถ๋ถ์ ๊ธฐ์กด ์ซ์์์ ์ญ์ ํด์ฃผ๋ฉด ๋๋ค.

์ฝ์ง ์ ๋ฌธ ์ฃผ๋์ด BE ๊ฐ๋ฐ์ ๐