-
[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
'알고리즘' 카테고리의 다른 글
[LeetCode] Single Number (0) 2022.05.03 [LeetCode] Reverse Bits (0) 2022.05.03 [LeetCode] Power of Two (0) 2022.05.03 70. Climbing Stairs (0) 2022.04.30 [LeetCode] 46. Permutations (0) 2022.04.28