File tree Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Original file line number Diff line number Diff line change @@ -46,3 +46,40 @@ def hammingWeight(self, n: int) -> int:
4646
4747sol = Solution ()
4848print (sol .hammingWeight (11 ))
49+
50+
51+ ### 6๊ธฐ ###
52+ from collections import Counter
53+
54+
55+ class Solution :
56+ def hammingWeight (self , n : int ) -> int :
57+
58+ binary = []
59+
60+ # ๋ฐ๋ณต - ์์/์ข
๋ฃ ์กฐ๊ฑด
61+ while n != 0 :
62+ # n/2์ ๋ชซ๊ณผ ๋๋จธ์ง ๋ ๋ค ํ์
63+ n , remainder = divmod (n , 2 )
64+ binary .append (remainder )
65+
66+ return Counter (binary )[1 ]
67+
68+
69+ # ๋นํธ ์ํํธ(Bit Shift) ์ฐ์ฐ
70+ def hammingWeight_bit (n : int ) -> int :
71+ count = 0
72+
73+ while n != 0 :
74+ count += n & 1 # 1. n์ ๊ฐ์ฅ ์ค๋ฅธ์ชฝ ๋นํธ๊ฐ 1์ด๋ฉด ๋ํจ
75+ n >>= 1 # 2. n์ ๋ชจ๋ ๋นํธ๋ฅผ ์ค๋ฅธ์ชฝ์ผ๋ก ํ ์นธ ์ด๋ (n์ 2๋ก ๋๋)
76+
77+ return count
78+
79+
80+ """ Q. binary๋ฅผ ์ ์ธํ ๋ list / str ์ค ํจ์จ์ ์ธ๊ฒ์?
81+ - list : O(1)
82+ - str
83+ - Python์์ ๋ฌธ์์ด์ ๋ถ๋ณ(Immutable) ์๋ฃํ
84+ - ๋ฌธ์์ด์ ๋ฌธ์๋ฅผ ํ๋์ฉ ์ถ๊ฐํ ๋๋ง๋ค ์๋ก์ด ๋ฌธ์์ด ์ ์ฒด๊ฐ ์์ฑ๋๊ณ ๊ธฐ์กด ๋ฌธ์์ด์ด ๋ณต์ฌ๋์ด์ผ ํจ O(n^2)
85+ """
You canโt perform that action at this time.
0 commit comments