Leetcode :: Convert a Number to Hexadecimal

์ˆ‘์ˆ‘ยท2021๋…„ 6์›” 27์ผ
0

์•Œ๊ณ ๋ฆฌ์ฆ˜

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

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ํ•˜์—ฌ ๋ณ€ํ™˜ํ•œ ๋ถ€๋ถ„์„ ๊ธฐ์กด ์ˆซ์ž์—์„œ ์‚ญ์ œํ•ด์ฃผ๋ฉด ๋œ๋‹ค.

profile
ํˆด ๋งŒ๋“ค๊ธฐ ์ข‹์•„ํ•˜๋Š” ์‚ฝ์งˆ ์ „๋ฌธ(...) ์ฃผ๋‹ˆ์–ด ๋ฐฑ์—”๋“œ ๊ฐœ๋ฐœ์ž์ž…๋‹ˆ๋‹ค.

0๊ฐœ์˜ ๋Œ“๊ธ€