Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit df8942f

Browse files
committedSep 3, 2018
Improved the countSetBit
1 parent 6b0bacd commit df8942f

File tree

1 file changed

+4
-4
lines changed

1 file changed

+4
-4
lines changed
 

‎src/algorithms/math/bits/countSetBits.js

+4-4
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,11 @@ export default function countSetBits(originalNumber) {
77
let number = originalNumber;
88

99
while (number) {
10-
// Add last bit of the number to the sum of set bits.
11-
setBitsCount += number & 1;
10+
// Using And operation on number with previous number.
11+
number &= (number - 1);
1212

13-
// Shift number right by one bit to investigate other bits.
14-
number >>= 1;
13+
// Increamenting number by 1.
14+
setBitsCount += 1;
1515
}
1616

1717
return setBitsCount;

0 commit comments

Comments
 (0)
Please sign in to comment.