Skip to content

Commit be185ac

Browse files
authored
Fix infinity loop with negative numbers (trekhleb#502)
* Update countSetBits.js * Update countSetBits.test.js
1 parent 5a3806f commit be185ac

File tree

2 files changed

+5
-1
lines changed

2 files changed

+5
-1
lines changed

src/algorithms/math/bits/__test__/countSetBits.test.js

+4
Original file line numberDiff line numberDiff line change
@@ -11,5 +11,9 @@ describe('countSetBits', () => {
1111
expect(countSetBits(21)).toBe(3);
1212
expect(countSetBits(255)).toBe(8);
1313
expect(countSetBits(1023)).toBe(10);
14+
expect(countSetBits(-1)).toBe(32);
15+
expect(countSetBits(-21)).toBe(30);
16+
expect(countSetBits(-255)).toBe(25);
17+
expect(countSetBits(-1023)).toBe(23);
1418
});
1519
});

src/algorithms/math/bits/countSetBits.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ export default function countSetBits(originalNumber) {
1111
setBitsCount += number & 1;
1212

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

1717
return setBitsCount;

0 commit comments

Comments
 (0)