diff --git a/Bit-Manipulation/BinaryCountSetBits.js b/Bit-Manipulation/BinaryCountSetBits.js index 60ae79123..7e77ec88b 100644 --- a/Bit-Manipulation/BinaryCountSetBits.js +++ b/Bit-Manipulation/BinaryCountSetBits.js @@ -9,6 +9,11 @@ function BinaryCountSetBits (a) { 'use strict' + + // check whether input is an integer, some non-integer number like, 21.1 have non-terminating binary expansions and hence their binary expansion will contain infinite ones, thus the handling of non-integers (including strings,objects etc. as it is meaningless) has been omitted + + if (!Number.isInteger(a)) throw new TypeError('Argument not an Integer') + // convert number into binary representation and return number of set bits in binary representation return a.toString(2).split('1').length - 1 } diff --git a/Bit-Manipulation/test/BinaryCountSetBits.test.js b/Bit-Manipulation/test/BinaryCountSetBits.test.js index 31740b66b..29c46e858 100644 --- a/Bit-Manipulation/test/BinaryCountSetBits.test.js +++ b/Bit-Manipulation/test/BinaryCountSetBits.test.js @@ -24,3 +24,9 @@ test('check BinaryCountSetBits of 0 is 0', () => { const res = BinaryCountSetBits(0) expect(res).toBe(0) }) +test('check BinaryCountSetBits of 21.1 throws error', () => { + expect(() => BinaryCountSetBits(21.1)).toThrow() +}) +test('check BinaryCountSetBits of {} throws error', () => { + expect(() => BinaryCountSetBits({})).toThrow() +})