Published:
Updated:

  • νŒŒμ΄μ¬μ—μ„œλŠ” ν•¨μˆ˜λ₯Ό μ΄μš©ν•˜λŠ” 방법이 더 λΉ λ₯΄κ³  κ°„νŽΈν•˜μ§€λ§Œ, Javaμ—μ„œλŠ” λ˜μ§€ μ•ŠμœΌλ‹ˆ λΉ„νŠΈλ‘œ κ³„μ‚°ν•˜λŠ” 방법도 κ΅¬ν˜„ν–ˆλ‹€.
  • 단, λΉ„νŠΈλ‘œ 계산할 λ•ŒλŠ” nκ³Ό n - 1을 AND 연산을 μ§„ν–‰ν•  μ‹œμ— μ–΄λ–»κ²Œ λ˜λŠ”μ§€ 미리 μ•Œκ³  μžˆμ–΄μ•Ό ν’€ 수 μžˆλ‹€.


Solution - FunctionPermalink

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

Solution - BitPermalink

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


ReferencePermalink

Leave a comment