Skip to content

Commit 46aac57

Browse files
committed
solve: NumberOf1Bit
1 parent 349ed86 commit 46aac57

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

โ€Žnumber-of-1-bits/b41-41.ts

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
function hammingWeight(n: number): number {
2+
3+
// ํ’€์ด 1:
4+
// binary๋กœ ๋ณ€ํ™˜ ํ›„ 1 count
5+
// ์‹œ๊ฐ„ ๋ณต์žก๋„: O(log n)
6+
// ๊ณต๊ฐ„ ๋ณต์žก๋„: O(log n)
7+
const getResult1 = () => {
8+
const binaryNum = n.toString(2);
9+
10+
let count = 0;
11+
12+
for(let i = 0; i < binaryNum.length; i++) {
13+
if(binaryNum.charAt(i) === '1') {
14+
count++
15+
}
16+
}
17+
18+
return count;
19+
};
20+
21+
// ํ’€์ด 2:
22+
// ๋น„ํŠธ ์—ฐ์‚ฐ์„ ํ™œ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค๊ณ  ํ•จ (From GPT)
23+
// ์‹œ๊ฐ„ ๋ณต์žก๋„: O(log n)
24+
// ๊ณต๊ฐ„ ๋ณต์žก๋„: O(1)
25+
// const getResult2 = () => {
26+
// let count = 0;
27+
28+
// while (n !== 0) {
29+
// count += n & 1;
30+
// n >>>= 1;
31+
// }
32+
33+
// return count;
34+
// }
35+
36+
return getResult1();
37+
// return getResult2();
38+
};

0 commit comments

Comments
ย (0)