File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ class Solution :
2+ def hammingWeight (self , n : int ) -> int :
3+ """
4+ ์ฃผ์ด์ง ์ซ์์ ์ด์ง ํํ์์, 1์ ๊ฐ์๋ฅผ ๊ณ์ฐํ๋ ํจ์
5+ ์) 11 -> 1011 => 3
6+
7+ ๋ฐฉ๋ฒ:
8+ 1. ์ซ์๋ฅผ ์ด์ง๋ฒ์ผ๋ก ๋ฐ๊ฟ์ 1์ ์ฐพ์ ๊ณ์ฐํ๊ธฐ
9+ - ์ด์ง๋ฒ์ผ๋ก ๋ฐ๊พธ๋ ๊ณผ์ ์์ ์ ์ฒด ์ํ๋ฅผ ํ๊ณ , 1์ ์ฐพ์๋ ๋ ์ํํด์ผํ .
10+ -> ํ๋ฒ์ ํด๊ฒฐํ ์ ์์๊น?
11+ 2. ์ซ์๋ฅผ ์ง์ ๋นํธ์ฐ์ฐํ๋ฉฐ ๊ณ์ฐํ๊ธฐ
12+ - ์ซ์๋ฅผ bitshiftํ๋ฉด์ ๋ง์ง๋ง ๋นํธ๊ฐ 1์ธ์ง ์๋์ง ์ฐพ๊ธฐ
13+ - 1์ด๋ฉด count + 1
14+ -> ์๊ฐ ๋ณต์ก๋ O(k) (k๋ ๋นํธ๊ธธ์ด), ๊ณต๊ฐ๋ณต์ก๋ O(1)
15+
16+ Args:
17+ n(int): ์์
18+
19+ Returns:
20+ int: ์ด์ง ํํ์์ 1์ ๊ฐ์
21+ """
22+ curr = n
23+ count = 0
24+ while curr > 0 :
25+ if curr & 1 == 1 :
26+ count += 1
27+ curr = curr >> 1
28+ return count
You canโt perform that action at this time.
0 commit comments