Here is the implementation:
function isPowerOfTwo(n):
return n > 0 and (n & (n - 1)) == 0
This runs in time. No loops needed.
Alternative: n > 0 && (highestOneBit(n) == n) or check if n is in the set .
##### ###### ##### ### # # ### # # ###### ## ## ## ## ## ## ## # # # # # ## ##### #### ##### # # # # # # # #### ## # ## ## ## ## # # # # # ## ## # ###### ## ### # ### # ######
##### ###### ##### ### # # ### # # ###### ## ## ## ## ## ## ## # # # # # ## ##### #### ##### # # # # # # # #### ## # ## ## ## ## # # # # # ## ## # ###### ## ### # ### # ######
Here is the implementation:
function isPowerOfTwo(n):
return n > 0 and (n & (n - 1)) == 0
This runs in time. No loops needed.
Alternative: n > 0 && (highestOneBit(n) == n) or check if n is in the set .