forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKwonNayeon.py
More file actions
51 lines (39 loc) ยท 1.45 KB
/
KwonNayeon.py
File metadata and controls
51 lines (39 loc) ยท 1.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
"""
Constraints:
- The input must be a binary string of length 32
<Solution 1>
Time Complexity: O(1)
- ํญ์ ๊ณ ์ ๋ 32๋นํธ ๋ฌธ์์ด์ ๋ํด ์ฐ์ฐํ๋ฏ๋ก ์์ ์๊ฐ
Space Complexity: O(1)
- 32๋นํธ ๊ณ ์ ํฌ๊ธฐ์ ๋ฌธ์์ด ์ฐ์ฐ๋ง ์ฌ์ฉํ๋ฏ๋ก ์์ ๊ณต๊ฐ
ํ์ด ๋ฐฉ๋ฒ:
1. format(n, '032b')๋ฅผ ์ฌ์ฉํด ์
๋ ฅ๋ฐ์ ์ ์๋ฅผ 32๋นํธ ์ด์ง์ ๋ฌธ์์ด๋ก ๋ณํํจ
2. ๋ฌธ์์ด ์ฌ๋ผ์ด์ฑ [::-1]์ผ๋ก ๋นํธ๋ฅผ ๋ค์ง์
3. int(reversed_binary, 2)๋ก ๋ค์ง์ ์ด์ง์ ๋ฌธ์์ด์ ๋ค์ ์ ์๋ก ๋ณํํจ
"""
class Solution:
def reverseBits(self, n: int) -> int:
binary = format(n, '032b')
reversed_binary = binary[::-1]
return int(reversed_binary, 2)
# ์ฝ๋๋ฅผ ๊ฐ๊ฒฐํ๊ฒ ์ ๋ฆฌํ ๋ฒ์
class Solution:
def reverseBits(self, n: int) -> int:
return int(format(n, '032b')[::-1], 2)
"""
<Solution 2>
Time Complexity: O(1)
- ๊ฐ ๋ฐ๋ณต์์ ๋นํธ ์ฐ์ฐ์ ์์ ์๊ฐ์ด ๊ฑธ๋ฆผ
Space Complexity: O(1)
- ์ฌ์ฉ๋๋ ๋ณ์๋ result์ ์
๋ ฅ๊ฐ n๋ฐ์ ์์
ํ์ด ๋ฐฉ๋ฒ:
- ...
"""
class Solution:
def reverseBits(self, n: int) -> int:
result = 0
for i in range(32):
result <<= 1 # ๊ฒฐ๊ณผ๋ฅผ ์ผ์ชฝ์ผ๋ก ํ ์นธ ๋ฐ๊ณ
result |= n & 1 # n์ ๋ง์ง๋ง ๋นํธ๋ฅผ ๊ฒฐ๊ณผ์ ์ถ๊ฐ
n >>= 1 # n์ ์ค๋ฅธ์ชฝ์ผ๋ก ํ ์นธ ๋ฐ์ด ๋ค์ ๋นํธ๋ก ์ด๋
return result