File tree Expand file tree Collapse file tree 1 file changed +51
-0
lines changed
Expand file tree Collapse file tree 1 file changed +51
-0
lines changed Original file line number Diff line number Diff line change 1+
2+
3+
4+ //ํ์ด1. ๋๋จธ์ง์ ๋ชซ์ ์ด์ฉํ ๊ฐ์ ๊ตฌํ๊ธฐ
5+
6+ /**
7+ * @param {number } n
8+ * @return {number }
9+ */
10+ var hammingWeight = function ( n ) {
11+ let remain = n ;
12+ let count = 0 ;
13+ while ( remain ) {
14+ if ( remain == 2 || remain == 1 ) {
15+ count += 1 ;
16+ break ;
17+ }
18+ if ( remain % 2 == 1 ) {
19+ count += 1
20+ }
21+ remain = Math . floor ( remain / 2 )
22+ }
23+ return count ;
24+ } ;
25+ /*2์ง๋ฒ์ ๊ตฌํ ๋, ๋๋จธ์ง๊ฐ 1์ผ๋๋ง๋ค count++ ํด์ฃผ๊ณ ,
26+ ๋ง์ง๋ง์ 2๋ 1์ด ๋จ์ผ๋ฉด count ++ ํ๊ณ break ํด์ฃผ๋ฉด ๋๋ค.
27+
28+ ์
๋ ฅ ๊ฐ์ ๋ฐ์ผ๋ก ๋๋๊ธฐ ๋๋ฌธ์ ์๊ฐ ๋ณต์ก๋๋ O(log n)
29+ ๊ณต๊ฐ๋ณต์ก๋ O(1)
30+ */
31+
32+ //ํ์ด 2. n์ ์ด์ง์์์ ๊ฐ์ฅ ์ค๋ฅธ์ชฝ 1๋นํธ๋ฅผ ํ๋์ฉ ์ ๊ฑฐํ์ฌ 1์ ๊ฐ์๋ฅผ ์ธ๋ ๋ฐฉ๋ฒ
33+
34+ /**
35+ * @param {number } n
36+ * @return {number }
37+ */
38+ var hammingWeight = function ( n ) {
39+ //์ ์ n์ด ์ฃผ์ด์ก์๋, 1์ ๊ฐ์?
40+ let count = 0 ;
41+ while ( n !== 0 ) {
42+ n = n & ( n - 1 ) ;
43+ count ++ ;
44+ }
45+ return count
46+ } ;
47+
48+ /*
49+ ์๊ฐ๋ณต์ก๋: O(k) : ์ฌ๊ธฐ์ k๋ n์ ํฌํจ๋ 1์ ๊ฐ์
50+ ๊ณต๊ฐ๋ณต์ก๋: O(1)
51+ */
You canโt perform that action at this time.
0 commit comments