This is the first blog post, and what I want to write is an algorithm that I learned today: no arithmetic operator is used to determine whether a number is a power of two;
public static bool Poweroftwo (int x) {return (X & (x-1)) = = 0;}
X if the power of 2, then the X is converted into a binary number only the first is 1 other bits are 0 (4 100,8 1000 16 10000), then X-1 is a first 0 other bits are 1 of the number (3 011, 7 0111) This form of
If X is a power of 2 then X and (X-1) do with the value returned by the operation must be 0. This allows you to quickly determine whether a number is a power of 2.
Statistics attach code with complex methods
int fun (n) {/* input n, if it is an integer power of 2, 1 is returned, otherwise 0 */int M is returned; M=n;for (;;) {if (m== 1) return 1;if (m%2 = = 1) return 0ELSEM=M/2;}}
How to determine whether a number is a power of two without arithmetic operators?