Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to determine if a given number is a power of two?

Tags:

javascript

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 ?

like image 877
Marco V Avatar asked Jun 18 '15 19:06

Marco V


1 Answers

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:

  • This will not be 100% true for programming, mathematical, [also read 'interviewing']. Some edge cases not handled by this are decimals (0.1, 0.2, 0.8…) or zero values (0, 0.0, …)
like image 79
thefourtheye Avatar answered Sep 30 '22 15:09

thefourtheye