Dar*_*ust 6

看看Bit Twiddling Hacks:

unsigned int v; // we want to see if v is a power of 2
bool f;         // the result goes here 

f = (v & (v - 1)) == 0;
Run Code Online (Sandbox Code Playgroud)

请注意,此处0被错误地视为2的幂.要解决这个问题,请使用:

f = v && !(v & (v - 1));
Run Code Online (Sandbox Code Playgroud)