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.
ํ ๋ง๋๋ก ์ซ์๋ฅผ 16์ง์๋ก ๋ณํํ๋, ์์๋ 2์ ๋ณด์๋ฒ์ ๋ฐ๋ผ๋ผ.
2์ ๋ณด์๋ก ์ด์งํํด์ ํํํ๋ ๋ถ๋ถ์ ์ปดํจํฐ๊ฐ ์๋์ผ๋ก ํด์ค๋ค..
์ฐ๋ฆฌ๊ฐ ๊ณ ๋ คํ ๊ฑด, 16์ง์๋ก ๋๋ ํํํ๋ ๋ถ๋ถ๋ง ํ๋ฉด ๋๋ค.
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ํ์ฌ ๋ณํํ ๋ถ๋ถ์ ๊ธฐ์กด ์ซ์์์ ์ญ์ ํด์ฃผ๋ฉด ๋๋ค.