File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -20,3 +20,27 @@ def hammingWeight(self, n: int) -> int:
2020 n = n // 2
2121
2222 return bits_sum
23+
24+
25+ # 7๊ธฐ ํ์ด
26+ # ์๊ฐ ๋ณต์ก๋: O(log n)
27+ # - 2๋ก ๊ณ์ ๋๋๊ณ , ์ด๋ 2์ง์ ์๋ฆฟ์ ๋งํผ ๋ฐ๋ณต
28+ # ๊ณต๊ฐ ๋ณต์ก๋: O(1)
29+ # - ๊ณ ์ ๋ ๋ณ์(quotient, remainder)๋ง ์ฌ์ฉ
30+ class Solution :
31+ def hammingWeight (self , n : int ) -> int :
32+ # 10์ง์๋ฅผ 2์ง์๋ก ๋ณํํ๋ ๊ณผ์ ์ 2๋ก ๊ณ์ ๋๋๋ฉด์ ๊ทธ ๋๋จธ์ง ๊ฐ๋ค์ ์์ฐจ์ ์ผ๋ก ๋์ดํ๋ ๊ฒ์ด๋ค.
33+ # ์ด ๋ ๋ฌธ์์ด๋ก ๋ง๋ค์ง ์๊ณ ๋ฐ๋ก result์ ๋ํด๊ฐ๋ฉด ๋ต์ด ๋ ์ ์์
34+ result = 0
35+
36+ while n > 0 :
37+ # ๋ชซ๊ณผ ๋๋จธ์ง ๊ณ์ฐ
38+ quotient , remainder = n // 2 , n % 2
39+
40+ # ๋๋จธ์ง๋ result์ ๋ํจ
41+ result += remainder
42+
43+ # ๋ชซ์ ๋ค์ ํผ์ ์๋ก ์ฌ์ฉ
44+ n = quotient
45+
46+ return result
You canโt perform that action at this time.
0 commit comments