Skip to content

Commit 78064bb

Browse files
committed
Number of 1 Bits solution
1 parent 78cdd14 commit 78064bb

File tree

1 file changed

+16
-0
lines changed

1 file changed

+16
-0
lines changed

number-of-1-bits/kimyoung.js

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
var hammingWeight = function (n) {
2+
let bitVal = n.toString(2); // convert input value to bit
3+
let setBits = 0;
4+
for (const char of bitVal) { // iterate through the string bit value to check the number of "1"s
5+
if (char === "1") setBits++; // increment if char === "1"
6+
}
7+
return setBits;
8+
};
9+
10+
// test cases
11+
console.log(hammingWeight(11)); // 3
12+
console.log(hammingWeight(128)); // 1
13+
console.log(hammingWeight(2147483645)); // 30
14+
15+
// space - O(1) - created only constant variables
16+
// time - O(n) - iterate through the bitVal string (larger the number the longer the string)

0 commit comments

Comments
 (0)