Today I needed a simple algorithm for checking if a number is a power of 2.
The algorithm needs to be:
ulong
in this approach , you can check if there is only 1 set bit in the integer and the integer is > 0 (c++).
bool is_pow_of_2(int n){ int count = 0; for(int i = 0; i < 32; i++){ count += (n>>i & 1); } return count == 1 && n > 0; }