From be185ac9afab48cb3a7b589ac6d9f6c8a3385098 Mon Sep 17 00:00:00 2001 From: Alexey Onikov <52637988+onicat@users.noreply.github.com> Date: Fri, 21 Aug 2020 08:21:20 +0300 Subject: [PATCH] Fix infinity loop with negative numbers (#502) * Update countSetBits.js * Update countSetBits.test.js --- src/algorithms/math/bits/__test__/countSetBits.test.js | 4 ++++ src/algorithms/math/bits/countSetBits.js | 2 +- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/src/algorithms/math/bits/__test__/countSetBits.test.js b/src/algorithms/math/bits/__test__/countSetBits.test.js index fb29cb09..f6770ae2 100644 --- a/src/algorithms/math/bits/__test__/countSetBits.test.js +++ b/src/algorithms/math/bits/__test__/countSetBits.test.js @@ -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); }); }); diff --git a/src/algorithms/math/bits/countSetBits.js b/src/algorithms/math/bits/countSetBits.js index 6e24eebf..63839d4e 100644 --- a/src/algorithms/math/bits/countSetBits.js +++ b/src/algorithms/math/bits/countSetBits.js @@ -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;