Skip to content

Commit f54ec27

Browse files
committed
add solution for reversing bits with two approaches
1 parent ecb4679 commit f54ec27

1 file changed

Lines changed: 29 additions & 0 deletions

File tree

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

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
"""
2+
# Approach
3+
1) ์ •์ˆ˜๋ฅผ ์ด์ง„ ๋ฌธ์ž์—ด๋กœ ๋ณ€ํ™˜ํ•œ ๋’ค,
4+
32๋น„ํŠธ๋กœ ๋งž์ถ”๊ณ  ๋’ค์ง‘์–ด์„œ ๋‹ค์‹œ ์ •์ˆ˜๋กœ ๋ณ€ํ™˜ํ•œ๋‹ค.
5+
6+
2) n์—์„œ ๋น„ํŠธ๋ฅผ ํ•˜๋‚˜์”ฉ ๊บผ๋‚ด์„œ res์— ์—ญ์ˆœ์œผ๋กœ ๋ถ™์ธ๋‹ค
7+
8+
# Complexity
9+
- Time complexity: O(1)
10+
- Space complexity: O(1)
11+
"""
12+
13+
14+
# 1
15+
class Solution:
16+
def reverseBits(self, n: int) -> int:
17+
b_num = format(n, "b")
18+
b_reversed = b_num.zfill(32)[::-1]
19+
return int(b_reversed, 2)
20+
21+
22+
# 2
23+
class Solution:
24+
def reverseBits(self, n: int) -> int:
25+
res = 0
26+
for _ in range(32):
27+
res = (res << 1) | (n & 1)
28+
n >>= 1
29+
return res

0 commit comments

Comments
ย (0)