From 46362e3d473c52fabe12231df5a0eb28ccf18ab1 Mon Sep 17 00:00:00 2001 From: Rahul Bhandari <90493221+imrahulkb@users.noreply.github.com> Date: Sat, 14 Oct 2023 22:24:11 +0530 Subject: [PATCH] chore: count set bits using bitwise ops (#1532) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Update BinaryCountSetBits.js * Use `let` instead of `var` --------- Co-authored-by: Lars Müller <34514239+appgurueu@users.noreply.github.com> --- Bit-Manipulation/BinaryCountSetBits.js | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/Bit-Manipulation/BinaryCountSetBits.js b/Bit-Manipulation/BinaryCountSetBits.js index e0a6d9414..b879f3bd6 100644 --- a/Bit-Manipulation/BinaryCountSetBits.js +++ b/Bit-Manipulation/BinaryCountSetBits.js @@ -14,8 +14,13 @@ function BinaryCountSetBits(a) { 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 - return a.toString(2).split('1').length - 1 + let count = 0 + while (a) { + a &= (a - 1) + count++ + } + + return count } export { BinaryCountSetBits }