Skip to content

Commit 8461271

Browse files
added check for Integer (#1137)
1 parent b71815d commit 8461271

File tree

2 files changed

+11
-0
lines changed

2 files changed

+11
-0
lines changed

Bit-Manipulation/BinaryCountSetBits.js

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,11 @@
99

1010
function BinaryCountSetBits (a) {
1111
'use strict'
12+
13+
// 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
14+
15+
if (!Number.isInteger(a)) throw new TypeError('Argument not an Integer')
16+
1217
// convert number into binary representation and return number of set bits in binary representation
1318
return a.toString(2).split('1').length - 1
1419
}

Bit-Manipulation/test/BinaryCountSetBits.test.js

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,3 +24,9 @@ test('check BinaryCountSetBits of 0 is 0', () => {
2424
const res = BinaryCountSetBits(0)
2525
expect(res).toBe(0)
2626
})
27+
test('check BinaryCountSetBits of 21.1 throws error', () => {
28+
expect(() => BinaryCountSetBits(21.1)).toThrow()
29+
})
30+
test('check BinaryCountSetBits of {} throws error', () => {
31+
expect(() => BinaryCountSetBits({})).toThrow()
32+
})

0 commit comments

Comments
 (0)