알고리즘

[LeetCode] Number of 1 Bits

유병각 2022. 5. 3. 01:44

191. Number of 1 Bits

방법_#1

파이썬에서 정수를 2진수로 변환하는 bin 함수를 사용한다.
bin(num:int) => string (2진수)

class Solution:
    def hammingWeight(self, n: int) -> int:
        c = collections.Counter(bin(n)[2:])
        return c["1"]

방법_#2

비트 shift 를 활용한다

import collections

class Solution:
    def hammingWeight(self, n: int) -> int:
        cnt = 0
        while (n):
            if (n & 1):
                cnt += 1
            n = n >> 1
        return cnt