Skip to content

Commit cfdf2e5

Browse files
committed
solve(w08): 190. Reverse Bits
1 parent 5f684be commit cfdf2e5

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

reverse-bits/seungriyou.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
# https://leetcode.com/problems/reverse-bits/
2+
3+
class Solution:
4+
def reverseBits_32(self, n: int) -> int:
5+
"""
6+
[Complexity]
7+
- TC: O(32)
8+
- SC: O(1)
9+
10+
[Approach]
11+
n의 맨 오른쪽 bit부터 res의 맨 왼쪽에 붙여나가기
12+
"""
13+
res = 0
14+
for i in range(32):
15+
res |= ((n >> i) & 1) << (31 - i)
16+
return res
17+
18+
def reverseBits(self, n: int) -> int:
19+
"""
20+
[Complexity]
21+
- TC: O(16)
22+
- SC: O(1)
23+
24+
[Approach]
25+
n의 바깥쪽에서부터 two pointer 처럼 res에 모으기
26+
"""
27+
res = 0
28+
for i in range(16):
29+
left = (n >> (31 - i)) & 1
30+
right = (n >> i) & 1
31+
res |= (left << i) | (right << (31 - i))
32+
return res

0 commit comments

Comments
 (0)