I need to return true if the n is a power of two and false otherwise. It should go something like:
function PowerOfTwo(n){
//code here
}
This is the way I currently do it :
function isPowerOfTwo(n){
var x = Math.pow(2, Math.round(Math.log(n) / Math.log(2)));
return x;
}
Are there any more effective ways ?
Source: Bit twiddling Hacks,
function powerOf2(v) {
return v && !(v & (v - 1));
}
You just bitwise AND the previous number with the current number. If the result is falsy, then it is a power of 2.
The explanation is in this answer.
Note:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With