File tree Expand file tree Collapse file tree 1 file changed +52
-0
lines changed Expand file tree Collapse file tree 1 file changed +52
-0
lines changed Original file line number Diff line number Diff line change 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
You canโt perform that action at this time.
0 commit comments