Published:
Updated:

  • ํŒŒ์ด์ฌ์—์„œ๋Š” ํ•จ์ˆ˜๋ฅผ ์ด์šฉํ•˜๋Š” ๋ฐฉ๋ฒ•์ด ๋” ๋น ๋ฅด๊ณ  ๊ฐ„ํŽธํ•˜์ง€๋งŒ, Java์—์„œ๋Š” ๋˜์ง€ ์•Š์œผ๋‹ˆ ๋น„ํŠธ๋กœ ๊ณ„์‚ฐํ•˜๋Š” ๋ฐฉ๋ฒ•๋„ ๊ตฌํ˜„ํ–ˆ๋‹ค.
  • ๋‹จ, ๋น„ํŠธ๋กœ ๊ณ„์‚ฐํ•  ๋•Œ๋Š” n๊ณผ n - 1์„ AND ์—ฐ์‚ฐ์„ ์ง„ํ–‰ํ•  ์‹œ์— ์–ด๋–ป๊ฒŒ ๋˜๋Š”์ง€ ๋ฏธ๋ฆฌ ์•Œ๊ณ  ์žˆ์–ด์•ผ ํ’€ ์ˆ˜ ์žˆ๋‹ค.


Solution - Function

class Solution:
    def hammingWeight(self, n: int) -> int:
        return bin(n).count('1')

Solution - Bit

class Solution:
    def hammingWeight(self, n: int) -> int:
        answer = 0

        # n๊ณผ n - 1์— ๋Œ€ํ•˜์—ฌ AND ์—ฐ์‚ฐ์„ ์ง„ํ–‰ -> ๋ฌด์กฐ๊ฑด ๋น„ํŠธ๊ฐ€ 1์”ฉ ์ œ๊ฑฐ๋จ
        # ์ฆ‰, ์ด ์—ฐ์‚ฐ์„ ์ง„ํ–‰ํ•œ ํšŸ์ˆ˜๋ฅผ answer์— ๋‹ด์œผ๋ฉด ๋˜๋Š” ๋ฌธ์ œ
        while n != 0:
            n = n & (n - 1)
            answer += 1

        return answer


Reference

Leave a comment