Skip to content

Instantly share code, notes, and snippets.

@BenDMyers
Last active October 11, 2021 05:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BenDMyers/227dd3f4b7c4d351316a4328f7b772a8 to your computer and use it in GitHub Desktop.
Save BenDMyers/227dd3f4b7c4d351316a4328f7b772a8 to your computer and use it in GitHub Desktop.
Determine whether a given number is odious (its binary expansion has an odd number of 1s)
/**
* Determines whether a given number is "odious" (its binary expansion has an odd number of ones)
* @param {number} num non-negative integer to test odiousness of
* @returns {boolean} whether `num` is odious
*/
function isOdious(num) {
let numberOf1Bits = 0;
// Binary expansions represent numbers as sums of powers of 2
// So we need to find how many powers of 2 can be subtracted from `num`
const exponentOfLargestPowerOf2 = Math.floor(Math.log2(num));
// Iterate over powers of 2, from the largest that could fit inside `num`
// all the way down to 2^0 = 1
for (let i = exponentOfLargestPowerOf2; i >= 0; i--) {
let currentPowerOf2 = Math.pow(2, i);
if (num - currentPowerOf2 >= 0) {
// The current power of 2 can be subtracted out from `num`,
// and is thus a "1" bit
num -= currentPowerOf2;
numberOf1Bits++;
}
}
return (numberOf1Bits % 2 === 1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment