Skip to content

Commit 4b659e7

Browse files
committed
Number of 1 Bits solution
1 parent d1500c2 commit 4b659e7

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
/**
2+
* ์ˆซ์ž๋ฅผ ์ด์ง„์ˆ˜๋กœ ๋ณ€ํ™˜ํ•˜๊ณ  1์˜ ๊ฐœ์ˆ˜๋ฅผ ์„ธ๋Š” ๋ฐฉ๋ฒ•
3+
* Follow up: ์ด ํ•จ์ˆ˜๊ฐ€ ์—ฌ๋Ÿฌ ๋ฒˆ ํ˜ธ์ถœ๋œ๋‹ค๋ฉด?
4+
*
5+
* ๋‹จ์ˆœํžˆ ๋ชจ๋“  ๋น„ํŠธ๋ฅผ ํ™•์ธํ•˜๋Š” ๋ฐฉ๋ฒ•: O(log n) ๋˜๋Š” 32๋น„ํŠธ ์ •์ˆ˜์˜ ๊ฒฝ์šฐ O(32)์˜ ์‹œ๊ฐ„ ๋ณต์žก๋„
6+
* โžก๏ธ Brian Kernighan์˜ ์•Œ๊ณ ๋ฆฌ์ฆ˜: O(k)
7+
* 1 ๋น„ํŠธ์˜ ์ˆ˜์— ๋น„๋ก€ํ•˜์—ฌ ์‹คํ–‰ ์‹œ๊ฐ„์ด ๊ฒฐ์ •
8+
*/
9+
10+
/**
11+
* @param {number} n
12+
* @return {number}
13+
*/
14+
var hammingWeight = function (n) {
15+
let count = 0;
16+
17+
while (n !== 0) {
18+
// n & (n-1)์€ n์˜ ๋งˆ์ง€๋ง‰ 1 ๋น„ํŠธ๋ฅผ ์ œ๊ฑฐ
19+
n = n & (n - 1);
20+
count++;
21+
}
22+
23+
return count;
24+
};

0 commit comments

Comments
ย (0)