Sky*_*ion 5 java math binary recursion performance
只是一个简单的布尔真/假非常有效会很好.我应该使用递归,还是有更好的方法来确定它?
Mit*_*eat 13
从这里:
确定整数是否为2的幂
Run Code Online (Sandbox Code Playgroud)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;
请注意,此处0被错误地视为2的幂.要解决这个问题,请使用:
Run Code Online (Sandbox Code Playgroud)f = v && !(v & (v - 1));
为什么这样做?只有两个整数幂才能设置一个位.减1会产生将该位更改为零并将其下方的所有位更改为1的效果.AND
使用原始数字将始终导致全部为零.