File tree Expand file tree Collapse file tree 1 file changed +19
-3
lines changed Expand file tree Collapse file tree 1 file changed +19
-3
lines changed Original file line number Diff line number Diff line change 15
15
2. 문자열 슬라이싱 [::-1]으로 비트를 뒤집음
16
16
3. int(reversed_binary, 2)로 뒤집은 이진수 문자열을 다시 정수로 변환함
17
17
"""
18
-
19
18
class Solution :
20
19
def reverseBits (self , n : int ) -> int :
21
20
@@ -24,12 +23,29 @@ def reverseBits(self, n: int) -> int:
24
23
reversed_binary = binary [::- 1 ]
25
24
26
25
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 )
27
32
"""
28
33
<Solution 2>
29
34
30
- Time Complexity:
35
+ Time Complexity: O(1)
36
+ - 각 반복에서 비트 연산은 상수 시간이 걸림
31
37
32
- Space Complexity:
38
+ Space Complexity: O(1)
39
+ - 사용되는 변수는 result와 입력값 n밖에 없음
33
40
34
41
풀이 방법:
42
+ - ...
35
43
"""
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
You can’t perform that action at this time.
0 commit comments