什么是最有效的方法来确定一个数字是2的幂?

Sky*_*ion 5 java math binary recursion performance

只是一个简单的布尔真/假非常有效会很好.我应该使用递归,还是有更好的方法来确定它?

Mit*_*eat 13

这里:

确定整数是否为2的幂

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)

为什么这样做?只有两个整数幂才能设置一个位.减1会产生将该位更改为零并将其下方的所有位更改为1的效果.AND使用原始数字将始终导致全部为零.