Today I needed a simple algorithm for checking if a number is a power of 2.
The algorithm needs to be:
ulong
Example
0000 0001 Yes 0001 0001 No
Algorithm
Using a bit mask, divide NUM the variable in binary
NUM
IF R > 0 AND L > 0: Return FALSE
Otherwise, NUM becomes the one that is non-zero
IF NUM = 1: Return TRUE
Otherwise, go to Step 1
Complexity
Time ~ O(log(d)) where d is number of binary digits
O(log(d))
d