Skip to content

Commit 96e08d3

Browse files
Jeehay28Jeehay28
authored andcommitted
Add number-of-1-bits solution in TypeScript
1 parent 0dab8a7 commit 96e08d3

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

number-of-1-bits/Jeehay28.ts

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
// Approach 2
2+
// 🗓️ 2025-04-15
3+
// ⏳ Time Complexity: O(log n)
4+
// 💾 Space Complexity: O(1)
5+
6+
function hammingWeight(n: number): number {
7+
// n(이진수) & 1 -> 1: 이진수 n의 마지막 비트가 1인 경우에만 1 반환
8+
// n(이진수) >> 1: 마지막 비트 제거
9+
// 🔍 In binary numbers:
10+
// Decimal: 11
11+
// Binary: 1 0 1 1
12+
// ↑ ↑
13+
// MSB LSB
14+
// (Most Sig.) (Least Sig.)
15+
// n & 1: only checks the least significant bit (LSB), if the LSB is 1, the result is 1.
16+
// n >>= 1: Each bit is moved one place to the right.
17+
18+
let count = 0;
19+
20+
while (n) {
21+
count += n & 1; // add 1 if the least significant bit of n is 1
22+
n >>= 1; // The LSB is removed (dropped).
23+
}
24+
25+
return count;
26+
}
27+
28+
29+
// Approach 1
30+
// 🗓️ 2025-04-15
31+
// ⏳ Time Complexity: O(log n)
32+
// 💾 Space Complexity: O(1)
33+
34+
// function hammingWeight(n: number): number {
35+
// // input: a positive number n
36+
// // output: the number of set bits in binary representation
37+
// // set bits: a bit in the binary representaton of a number that has a value of 1
38+
// // 11 -> 1011 -> 3
39+
40+
// let cnt = 0;
41+
// while (n > 0) {
42+
// if (n % 2 === 1) {
43+
// cnt += 1;
44+
// }
45+
// n = Math.floor(n / 2);
46+
// }
47+
48+
// return cnt;
49+
// }
50+

0 commit comments

Comments
 (0)