Fix infinity loop with negative numbers (#502)

* Update countSetBits.js

* Update countSetBits.test.js
This commit is contained in:
Alexey Onikov 2020-08-21 08:21:20 +03:00 committed by GitHub
parent 5a3806ff81
commit be185ac9af
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 5 additions and 1 deletions

View File

@ -11,5 +11,9 @@ describe('countSetBits', () => {
expect(countSetBits(21)).toBe(3);
expect(countSetBits(255)).toBe(8);
expect(countSetBits(1023)).toBe(10);
expect(countSetBits(-1)).toBe(32);
expect(countSetBits(-21)).toBe(30);
expect(countSetBits(-255)).toBe(25);
expect(countSetBits(-1023)).toBe(23);
});
});

View File

@ -11,7 +11,7 @@ export default function countSetBits(originalNumber) {
setBitsCount += number & 1;
// Shift number right by one bit to investigate other bits.
number >>= 1;
number >>>= 1;
}
return setBitsCount;