Skip to content

Commit 18c54a3

Browse files
committed
solve(w03): 191. Number of 1 Bits
1 parent d46d37e commit 18c54a3

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
# https://leetcode.com/problems/number-of-1-bits/
2+
3+
class Solution:
4+
def hammingWeight1(self, n: int) -> int:
5+
"""
6+
[Complexity]
7+
- TC: O(logn) (์–ด์ฐจํ”ผ O(1))
8+
- SC: O(1)
9+
10+
[Approach]
11+
Bit manipulation์„ ์ด์šฉํ•˜์—ฌ n์ด 0์ด ๋  ๋•Œ๊นŒ์ง€ ๋‹ค์Œ์„ ๋ฐ˜๋ณตํ•œ๋‹ค.
12+
1) ๋งจ ์˜ค๋ฅธ์ชฝ์˜ bit๊ฐ€ 1์ด๋ฉด res์— 1์„ ๋”ํ•˜๊ณ , 0์ด๋ฉด 0์„ ๋”ํ•œ๋‹ค.
13+
2) n์„ ์˜ค๋ฅธ์ชฝ์œผ๋กœ 1 shift ํ•œ๋‹ค.
14+
"""
15+
res = 0
16+
while n:
17+
res += n & 1
18+
n >>= 1
19+
return res
20+
21+
def hammingWeight2(self, n: int) -> int:
22+
"""
23+
[Complexity]
24+
- TC: O(k) (k = number of set bits)
25+
- SC: O(1)
26+
27+
[Approach] Brian Kernighan's Algorithm
28+
์˜ค๋ฅธ์ชฝ์—์„œ๋ถ€ํ„ฐ 1์ธ bit๋ฅผ ํ•˜๋‚˜์”ฉ ์ง€์›Œ๊ฐ€๋ฉฐ ๊ฐœ์ˆ˜๋ฅผ ์„ธ๋ฉด ๋œ๋‹ค.
29+
์ด๋•Œ, ์˜ค๋ฅธ์ชฝ์—์„œ๋ถ€ํ„ฐ 1์ธ bit๋ฅผ ์ง€์šฐ๊ธฐ ์œ„ํ•ด์„œ๋Š” n & n - 1 ์„ ํ•˜๋ฉด ๋œ๋‹ค.
30+
(ref: https://leetcode.com/problems/number-of-1-bits/solutions/4341511/faster-lesser-3-methods-simple-count-brian-kernighan-s-algorithm-bit-manipulation-explained)
31+
"""
32+
res = 0
33+
while n:
34+
n &= n - 1
35+
res += 1
36+
return res
37+
38+
def hammingWeight(self, n: int) -> int:
39+
"""
40+
[Complexity]
41+
- TC: O(logn) (์–ด์ฐจํ”ผ O(1))
42+
- SC: O(1)
43+
44+
[Approach]
45+
n์„ 2๋กœ ๋‚˜๋ˆ„๋ฉด์„œ ๊ทธ ๋‚˜๋จธ์ง€ ๊ฐ’์ด 1์ด๋ฉด res์— 1์„ ๋”ํ•˜๊ณ , 0์ด๋ฉด 0์„ ๋”ํ•œ๋‹ค.
46+
"""
47+
res = 0
48+
while n:
49+
d, m = divmod(n, 2)
50+
res += m
51+
n = d
52+
return res

0 commit comments

Comments
ย (0)