Skip to content

Commit 46362e3

Browse files
imrahulkbappgurueu
andauthored
chore: count set bits using bitwise ops (#1532)
* Update BinaryCountSetBits.js * Use `let` instead of `var` --------- Co-authored-by: Lars Müller <[email protected]>
1 parent 628c5ae commit 46362e3

File tree

1 file changed

+7
-2
lines changed

1 file changed

+7
-2
lines changed

Bit-Manipulation/BinaryCountSetBits.js

+7-2
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,13 @@ function BinaryCountSetBits(a) {
1414

1515
if (!Number.isInteger(a)) throw new TypeError('Argument not an Integer')
1616

17-
// convert number into binary representation and return number of set bits in binary representation
18-
return a.toString(2).split('1').length - 1
17+
let count = 0
18+
while (a) {
19+
a &= (a - 1)
20+
count++
21+
}
22+
23+
return count
1924
}
2025

2126
export { BinaryCountSetBits }

0 commit comments

Comments
 (0)