Skip to content

Commit 643b9c7

Browse files
author
bhan
committed
number of 1 bits solution
1 parent bd99c28 commit 643b9c7

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

number-of-1-bits/byol-han.js

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
/**
2+
* @param {number} n
3+
* @return {number}
4+
*/
5+
//1. divide the number by 2 and count the remainder
6+
var hammingWeight = function (n) {
7+
let count = 0;
8+
while (n > 0) {
9+
if (n % 2 === 1) {
10+
count++;
11+
}
12+
n = Math.floor(n / 2);
13+
}
14+
return count;
15+
};
16+
17+
//2. Count the number of set bits (1s) in the binary representation of n
18+
var hammingWeight = function (n) {
19+
return n.toString(2).split("1").length - 1;
20+
};
21+
22+
//3. bit manipulation
23+
var hammingWeight = function (n) {
24+
let count = 0;
25+
while (n > 0) {
26+
count += n & 1; // 마지막 비트가 1이면 count++
27+
n = n >>> 1; // 오른쪽으로 한 비트 이동 (2로 나눔)
28+
}
29+
return count;
30+
};

0 commit comments

Comments
 (0)