File tree Expand file tree Collapse file tree 1 file changed +50
-0
lines changed Expand file tree Collapse file tree 1 file changed +50
-0
lines changed Original file line number Diff line number Diff line change 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+
You can’t perform that action at this time.
0 commit comments