Skip to content

feat: new algorithm to count bits #1316

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions Bit-Manipulation/BinaryCountBitsRegex.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
/**
*author: nikolaospanagopoulos
*This script will use a RegEx to find number of 1s in a binary representation of a number
*I tried to think of every possible input
**/

const CountBitsWithRegex = (number) => {
if (typeof number !== 'number') {
// because an "" is evaluated to 0
throw new TypeError('Not a number')
}
if (isNaN(number)) {
// because even NaN is a number. Just not a valid one ex 0/0
throw new TypeError('Not a valid number')
}
if (!Number.isFinite(number)) {
// In Javascript a number other than 0, divided by 0 return Infinity
// if divided by -0 returns -Infinity
throw new TypeError('Not a valid number. Infinity. probably division by 0')
}
if (!Number.isInteger(number)) {
// because if it is floating point number it
// may have non terminating binary expansions
throw new TypeError('It is a floating point number')
}

// we use regular expression that will match all 1s. g means global match
return number.toString(2).match(/1/g)?.length || 0
}
export { CountBitsWithRegex }