C#数学问题:2的最小幂大于X?

bev*_*qua 3 c# math

    public int CalcBrackets(int teamCount)
    {
        int positions = 1;

        while (positions < teamCount)
            positions *= 2;

        return positions;
    }
Run Code Online (Sandbox Code Playgroud)

我想要的最小数字是2的幂,大于或等于teamCount.这真的是最好的方法吗?肯定看起来很可怕:(

fde*_*hin 10

如果你需要计算的最小功率2(不是倍数)小于teamCount,那么可能它是最好的方法.采用对数是一个很容易的操作,可能需要更多的时间,然后是一个简单的循环.

upd 这是一个使用按位运算的算法(C++)(http://aggregate.org/MAGIC/,Sext Next Largest Power of 2)

unsigned int nlpo2(unsigned int x)
{
    x--; // comment out to always take the next biggest power of two, even if x is already a power of two
    x |= (x >> 1);
    x |= (x >> 2);
    x |= (x >> 4);
    x |= (x >> 8);
    x |= (x >> 16);
    return (x+1);
}
Run Code Online (Sandbox Code Playgroud)

首先,它将数字的所有相关位设置为1(例如,0x3ff),然后将其递增(0x400)以获得2的幂.