Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit e8ce329

Browse files
committedMay 19, 2025·
Add second solution for Reverse Bits
1 parent d737da0 commit e8ce329

File tree

1 file changed

+19
-3
lines changed

1 file changed

+19
-3
lines changed
 

‎reverse-bits/KwonNayeon.py

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,6 @@
1515
2. 문자열 슬라이싱 [::-1]으로 비트를 뒤집음
1616
3. int(reversed_binary, 2)로 뒤집은 이진수 문자열을 다시 정수로 변환함
1717
"""
18-
1918
class Solution:
2019
def reverseBits(self, n: int) -> int:
2120

@@ -24,12 +23,29 @@ def reverseBits(self, n: int) -> int:
2423
reversed_binary = binary[::-1]
2524

2625
return int(reversed_binary, 2)
26+
27+
# 코드를 간결하게 정리한 버전
28+
class Solution:
29+
def reverseBits(self, n: int) -> int:
30+
31+
return int(format(n, '032b')[::-1], 2)
2732
"""
2833
<Solution 2>
2934
30-
Time Complexity:
35+
Time Complexity: O(1)
36+
- 각 반복에서 비트 연산은 상수 시간이 걸림
3137
32-
Space Complexity:
38+
Space Complexity: O(1)
39+
- 사용되는 변수는 result와 입력값 n밖에 없음
3340
3441
풀이 방법:
42+
- ...
3543
"""
44+
class Solution:
45+
def reverseBits(self, n: int) -> int:
46+
result = 0
47+
for i in range(32):
48+
result <<= 1 # 결과를 왼쪽으로 한 칸 밀고
49+
result |= n & 1 # n의 마지막 비트를 결과에 추가
50+
n >>= 1 # n을 오른쪽으로 한 칸 밀어 다음 비트로 이동
51+
return result

0 commit comments

Comments
 (0)
Please sign in to comment.