Want to add a "Killer" trick.
A function to check if a given positive integer is a power of 2
function isPowerofTwo(num){ if( num & (num-1) == 0 ) return true; return false; }
& used here is the Bitwise AND.
&
This is what the modulus operator % is for. By negating the check, you return 1 (true) or 0 (false) with: console.log(!num % 2)
%
console.log(!num % 2)
Modulus checks if the number is divisible by a number or not, It doesn't checks for exponent.
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Want to add a "Killer" trick.
A function to check if a given positive integer is a power of 2
&
used here is the Bitwise AND.This is what the modulus operator
%
is for. By negating the check, you return 1 (true) or 0 (false) with:console.log(!num % 2)
Modulus checks if the number is divisible by a number or not, It doesn't checks for exponent.