191 | Number of 1 Bits
https://leetcode.com/problems/number-of-1-bits/



작성 코드
class Solution:
def hammingWeight(self, n: int) -> int:
return(bin(n).count("1"))
- bin 을 통해 n 을 문자열로 변환하여 "1" count
bin(n)
>>> 1011
- bin() - 10진수 숫자를 이진수 문자열로 바꾸는 함수
- bin(n) 을 통해 앞의 0은 절삭됨
이상 코드
class Solution:
def hammingWeight(self, n: int) -> int:
num_of_1s = 0
for _ in range(32):
num_of_1s += (n & 1)
n = n >> 1
return num_of_1s
- 제약 사항에서 이진 문자열의 길이는 32라고 알려줌
- n & 1 을 통해 n의 끝자리가 1인지 판별
- >> 연산을 통해 비트를 오른쪽으로 옮김 (끝자리 탈락)
- 비트 연산을 잘 활용한 예제
학습
- bin 을 통해 10진수를 이진 문자열로 반환할 수 있음
- (n & 1) 을 통해 끝자리가 1인지 판별
- >> 비트 오른쪽으로, << 비트 왼쪽으로
반응형
'Algorithm > LeetCode' 카테고리의 다른 글
| [LeetCode] 695 | Max Area of Island (0) | 2022.03.17 |
|---|---|
| [LeetCode] 1822 | Sign of the Product of an Array (0) | 2022.03.15 |
| [LeetCode] 14 | Longest Common Prefix (0) | 2022.02.22 |
| [LeetCode] 561 | Array Partition I (0) | 2022.02.17 |
| [LeetCode] 13 | Roman to Integer (0) | 2022.01.28 |
댓글