Skip to content

Commit a874a1d

Browse files
committed
reverse-bits solution (py)
1 parent 7f329f5 commit a874a1d

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed

reverse-bits/hi-rachel.py

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
"""
2+
1. 입력받은 정수 n을 32비트 이진수로 바꾼다
3+
2. 이진수를 좌우로 뒤집는다 -> stack 활용
4+
2. 뒤집은 이진수의 정수값을 반환한다
5+
6+
항상 32비트이므로 상수 시간, 상수 공간
7+
TC: O(1)
8+
SC: O(1)
9+
"""
10+
11+
class Solution:
12+
def reverseBits(self, n: int) -> int:
13+
stack = []
14+
while len(stack) < 32:
15+
stack.append(n % 2)
16+
n //= 2
17+
18+
output, scale = 0, 1 # 결과, 2^0 = 1 시작
19+
while stack:
20+
output += stack.pop() * scale
21+
scale *= 2
22+
23+
return output
24+
25+
"""
26+
비트 연산자
27+
28+
쉬프트 연산자 - 정수 타입에만 사용 가능, 내부적으로 이진수로 작동
29+
<< 비트를 왼쪽으로 이동
30+
x << 1 == x * 2
31+
ex) 00001101 → 00011010
32+
33+
>> 비트를 오른쪽으로 이동
34+
x >> 1 == x // 2
35+
ex) 00001101 → 00000110
36+
37+
n & 1
38+
현재 n의 가장 오른쪽 비트 확인
39+
n & 1이 1이면 홀수, 0이면 짝수
40+
"""
41+
42+
class Solution:
43+
def reverseBits(self, n: int) -> int:
44+
stack = []
45+
while len(stack) < 32:
46+
stack.append(n & 1) # 마지막 비트 1이면 1, 0이면 0
47+
n >>= 1 # %= 2 와 같은 효과, 오른쪽 쉬프트
48+
49+
output, scale = 0, 1 # 결과, 2^0 = 1 시작
50+
while stack:
51+
output += stack.pop() * scale
52+
scale <<= 1 # *= 2 와 같은 효과
53+
54+
return output
55+
56+
# stack 공간 절약 풀이
57+
class Solution:
58+
def reverseBits(self, n: int) -> int:
59+
output = 0
60+
for _ in range(32):
61+
output <<= 1 # 왼쪽 쉬프트
62+
output |= (n & 1) # 논리 연산자 사용 (제일 마지막 비트가 1이라면 1, 0이라면 0)
63+
n >>= 1
64+
return output
65+
66+
# int, format 활용 풀이
67+
class Solution:
68+
def reverseBits(self, n: int) -> int:
69+
return int(format(n, "032b")[::-1], 2)

0 commit comments

Comments
 (0)