Skip to content

Commit 043d7c4

Browse files
committed
number of 1 bits solution
1 parent f88cc36 commit 043d7c4

1 file changed

Lines changed: 24 additions & 0 deletions

File tree

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
/**
2+
toString(2)์œผ๋กœ ํ•ด๊ฒฐํ–ˆ๋‹ค๊ฐ€ ๋‹ค๋ฅธ ๋ถ„์˜ ํ’€์ด๋ฅผ ๋ณด๊ณ  ๋‹ค์‹œ ํ’€์–ด๋ณด์•˜๋‹ค.
3+
4+
'๋น„ํŠธ ์—ฐ์‚ฐ์„ ํ†ตํ•œ ๊ณ„์‚ฐ'์ด๋‹ค.
5+
์ปดํ“จํ„ฐ์—์„œ ๋ชจ๋“  ์–ธ์–ด๋Š” 2์ง„๋ฒ•์œผ๋กœ ๋ณ€ํ™˜์ด ๋˜๋Š”๋ฐ, ์ด๋ฅผ ์ด์šฉํ•œ ํ”Œ์ด๋‹ค.
6+
๊ฐ€์žฅ ์˜ค๋ฅธ์ชฝ ๋น„ํŠธ๊ฐ€ 1์ธ ๊ฒฝ์šฐ์— count++, n์„ ์šฐ์ธก์œผ๋กœ 1์นธ shift.
7+
shift๋ฅผ ํ•˜๋ฉด ๊ฒฐ๊ตญ ๋‚จ๋Š” ์ˆซ์ž๋Š” 0์ด๊ธฐ ๋•Œ๋ฌธ์— ์ ์ ˆํ•œ ์กฐ๊ฑด์œผ๋กœ ๋ฃจํ”„๋ฅผ ๋น ์ ธ๋‚˜์˜จ๋‹ค.
8+
9+
๊ตณ์ด 2์ง„๋ฒ•์œผ๋กœ ๋ณ€ํ™˜ํ•˜์ง€ ์•Š๊ณ ๋„ ๊ณ„์‚ฐํ•  ์ˆ˜ ์žˆ์–ด์„œ ์ด๊ฒŒ ๋” ์ข‹์€ ํ’€์ด๋ผ ์ƒ๊ฐํ•˜์˜€๋‹ค.
10+
*/
11+
/**
12+
* @param {number} n
13+
* @return {number}
14+
*/
15+
function hammingWeight(n) {
16+
let count = 0;
17+
18+
while (n !== 0) {
19+
count += n & 1;
20+
n >>>= 1;
21+
}
22+
23+
return count;
24+
}

0 commit comments

Comments
ย (0)