javascript - What is the best way to determine if a given number is a power of two? -
i need return true if n power of 2 , false otherwise. should go like:
function poweroftwo(n){ //code here }
this way :
function ispoweroftwo(n){ var x = math.pow(2, math.round(math.log(n) / math.log(2))); return x; }
are there more effective ways ?
you can use ecmascript5 math.log
:
function poweroftwo(x) { return (math.log(x)/math.log(2)) % 1 === 0; }
remember, in math, logarithm arbitrary base, can divide log10 of operand (x
in case) log10 of base. , see if number regular integer (and not floating point), check if remainder 0 using modulus %
operator.
in ecmascript6 can this:
function poweroftwo(x) { return math.log2(x) % 1 === 0; }
see mdn docs math.log2
.
Comments
Post a Comment