SIGN IN SIGN UP

Algorithms and Data Structures implemented in JavaScript for beginners, following best practices.

34083 0 0 JavaScript
/*
author: vivek9patel
license: GPL-3.0 or later
This script will find number of 1's
2021-10-05 12:49:23 +05:30
in binary representation of given number
*/
2020-10-01 13:29:41 +05:30
function BinaryCountSetBits (a) {
'use strict'
2022-10-07 17:16:28 +05:30
// 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')
2021-10-05 12:49:23 +05:30
// convert number into binary representation and return number of set bits in binary representation
2020-10-01 13:29:41 +05:30
return a.toString(2).split('1').length - 1
}
export { BinaryCountSetBits }