mirror of
https://github.com/TheAlgorithms/JavaScript.git
synced 2025-07-06 01:18:23 +08:00
chore: count set bits using bitwise ops (#1532)
* Update BinaryCountSetBits.js * Use `let` instead of `var` --------- Co-authored-by: Lars Müller <34514239+appgurueu@users.noreply.github.com>
This commit is contained in:
@ -14,8 +14,13 @@ function BinaryCountSetBits(a) {
|
|||||||
|
|
||||||
if (!Number.isInteger(a)) throw new TypeError('Argument not an Integer')
|
if (!Number.isInteger(a)) throw new TypeError('Argument not an Integer')
|
||||||
|
|
||||||
// convert number into binary representation and return number of set bits in binary representation
|
let count = 0
|
||||||
return a.toString(2).split('1').length - 1
|
while (a) {
|
||||||
|
a &= (a - 1)
|
||||||
|
count++
|
||||||
|
}
|
||||||
|
|
||||||
|
return count
|
||||||
}
|
}
|
||||||
|
|
||||||
export { BinaryCountSetBits }
|
export { BinaryCountSetBits }
|
||||||
|
Reference in New Issue
Block a user