We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent bd99c28 commit 643b9c7Copy full SHA for 643b9c7
number-of-1-bits/byol-han.js
@@ -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
19
+ return n.toString(2).split("1").length - 1;
20
21
22
+//3. bit manipulation
23
24
25
26
+ count += n & 1; // 마지막 비트가 1이면 count++
27
+ n = n >>> 1; // 오른쪽으로 한 비트 이동 (2로 나눔)
28
29
30
0 commit comments