Skip to content

Commit 07c5a56

Browse files
authored
number-of-1-bits solution
1 parent b498418 commit 07c5a56

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
function hammingWeight(n: number): number {
2+
// ์ฒซ์‹œ๋„: ์‹œ๊ฐ„/๊ณต๊ฐ„ ๋ณต์žก๋„ O(log n)
3+
// const toBinary = n.toString(2).split('').map(Number);
4+
// let answer = 0;
5+
6+
// for (let i=0; i<toBinary.length; i++) {
7+
// if (toBinary[i] === 1) answer++;
8+
// }
9+
10+
// return answer;
11+
12+
// ๋‘๋ฒˆ์งธ ์‹œ๋„: ์‹œ๊ฐ„ ๋ณต์žก๋„: O(log n), ๊ณต๊ฐ„ ๋ณต์žก๋„: O(1)
13+
// let count = 0;
14+
15+
// while(n>0) {
16+
// if (n%2 === 1) count++;
17+
// n = Math.floor(n/2);
18+
// }
19+
20+
// return count;
21+
22+
// ์‹œ๊ฐ„, ๊ณต๊ฐ„ ๋ณต์žก๋„๋Š” ๋‘๋ฒˆ์งธ์™€ ๊ฐ™์ง€๋งŒ, ๋น„ํŠธ ์—ฐ์‚ฐ์ด CPU์—์„œ ์ง์ ‘ ์ฒ˜๋ฆฌ๋˜๋Š” ์ €์ˆ˜์ค€ ๋ช…๋ น์–ด๋กœ ์ˆ˜ํ–‰๋˜์–ด ์—ฐ์‚ฐ ๋น„์šฉ์ด ๋‚ฎ๊ธฐ ๋•Œ๋ฌธ์— ์‚ฐ์ˆ ์—ฐ์‚ฐ๋ณด๋‹ค ๋” ๋น ๋ฆ„
23+
let count = 0;
24+
25+
while (n > 0) {
26+
count += n & 1; // ๋งˆ์ง€๋ง‰ ๋น„ํŠธ๊ฐ€ 1์ด๋ฉด count++
27+
n >>>= 1; // ๋ถ€ํ˜ธ ์—†๋Š” ๋น„ํŠธ ์‹œํ”„ํŠธ
28+
}
29+
30+
return count;
31+
};

0 commit comments

Comments
ย (0)