Skip to content

Commit dc8c121

Browse files
committed
feat: [Week 03-2] solve reverse-bits
1 parent 2fc5ef0 commit dc8c121

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

โ€Žreverse-bits/Chaedie.pyโ€Ž

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
"""
2+
1. ํ•™์Šต์€ ์ง„ํ–‰ํ–ˆ์ง€๋งŒ, ์Šค์Šค๋กœ ์™„๋ฒฝํ•˜๊ฒŒ ํ’€์ง€ ๋ชปํ–ˆ์Šต๋‹ˆ๋‹ค.
3+
๋‹ค์Œ์ฃผ์— bit ์—ฐ์‚ฐ์œผ๋กœ ๋‹ค์‹œ ํ’€์–ด๋ณผ ์˜ˆ์ •์ž…๋‹ˆ๋‹ค.
4+
"""
5+
6+
7+
class Solution:
8+
9+
# ์•Œ๊ณ ๋‹ฌ๋ ˆ ํ’€์ด 1) Stack
10+
def reverseBits(self, n: int) -> int:
11+
stack = []
12+
while len(stack) < 32:
13+
stack.append(n % 2)
14+
n //= 2
15+
16+
result, scale = 0, 1
17+
while stack:
18+
result += stack.pop() * scale
19+
scale *= 2
20+
return result
21+
22+
# ์•Œ๊ณ ๋‹ฌ๋ ˆ ํ’€์ด 2) bit manipulation
23+
def reverseBits(self, n: int) -> int:
24+
result = 0
25+
print(n)
26+
for i in range(32):
27+
print(result)
28+
result <<= 1
29+
result |= n & 1
30+
n >>= 1
31+
return result
32+
33+
# NeetCode ํ’€์ด
34+
def reverseBits(self, n: int) -> int:
35+
res = 0
36+
37+
for i in range(32):
38+
bit = (n >> i) & 1
39+
res = res | (bit << (31 - i))
40+
return res
41+
42+
# ์Šค์Šค๋กœ ํ’€๊ธฐ
43+
# ํ•œ๋ฒˆ ๋” ํ’€ ์—์ •์ž…๋‹ˆ๋‹ค.
44+
def reverseBits(self, n: int) -> int:
45+
result = 0
46+
for i in range(32):
47+
result = result << 1
48+
result = result | (n & 1)
49+
n = n >> 1
50+
return result

0 commit comments

Comments
ย (0)