Skip to content

Commit e8ce329

Browse files
committed
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)