https://youtu.be/UcoN6UjAI64?si=QcqwmCh09NAZbJMq
class Solution:
def reverseBits(self, n: int) -> int:
# 1과 & 오퍼레이션하면, 해당 비트 나옴
# << 1: 왼쪽 1칸 쉬프트
res = 0
# 32비트 숫자를 처리하기 위해 32번 반복
for i in range(32):
# (n >> i): n을 i만큼 오른쪽으로 쉬프트하면 i번째 비트가 오른쪽 끝에 위치함
# & 1: AND 연산을 통해 해당 비트를 추출 (나머지는 0)
bit = (n >> i) & 1
# 추출한 비트를 뒤집은 위치로 이동 (왼쪽에서부터 채우기)
# 31-i: 0번째 비트는 31번째에, 1번째 비트는 30번째에 위치하게 됨
res = res | (bit << (31 - i))
# 최종 결과 반환
return res
내 코드
class Solution:
def reverseBits(self, n: int) -> int:
# The input must be a binary string of length 32
res = 0
for i in range(32):
bit = n & 1 # 제일 오른쪽 비트가 1인지 0인지
bit = bit << (31-i) # 그 비트를 왼쪽으로 밀고, << (32-i) 하면 안됨
res = res | bit # 추가
n = n>>1
return res
'LeetCode > 주제별 보충' 카테고리의 다른 글
BST: 4. Median of Two Sorted Arrays ★★★★★ (2) | 2024.12.21 |
---|---|
Bit: 191. Number of 1 Bits (0) | 2024.12.17 |
Graphs(싸이클탐지): 207. Course Schedule ★★★ (0) | 2024.12.16 |
Graphs: 133. Clone Graph (0) | 2024.12.16 |
Graphs: 130. Surrounded Regions★★ (0) | 2024.12.16 |