mirror of
https://github.moeyy.xyz/https://github.com/trekhleb/javascript-algorithms.git
synced 2024-12-27 07:31:17 +08:00
Fix infinity loop with negative numbers (#502)
* Update countSetBits.js * Update countSetBits.test.js
This commit is contained in:
parent
5a3806ff81
commit
be185ac9af
@ -11,5 +11,9 @@ describe('countSetBits', () => {
|
|||||||
expect(countSetBits(21)).toBe(3);
|
expect(countSetBits(21)).toBe(3);
|
||||||
expect(countSetBits(255)).toBe(8);
|
expect(countSetBits(255)).toBe(8);
|
||||||
expect(countSetBits(1023)).toBe(10);
|
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);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
@ -11,7 +11,7 @@ export default function countSetBits(originalNumber) {
|
|||||||
setBitsCount += number & 1;
|
setBitsCount += number & 1;
|
||||||
|
|
||||||
// Shift number right by one bit to investigate other bits.
|
// Shift number right by one bit to investigate other bits.
|
||||||
number >>= 1;
|
number >>>= 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
return setBitsCount;
|
return setBitsCount;
|
||||||
|
Loading…
Reference in New Issue
Block a user