gpt4 book ai didi

C#数学题: smallest power of 2 bigger than X?

转载 作者:行者123 更新时间:2023-11-30 13:28:28 29 4
gpt4 key购买 nike

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

while (positions < teamCount)
positions *= 2;

return positions;
}

我想要大于或等于 teamCount 的 2 的幂的最小数字。这真的是最好的方法吗?它确实看起来很可怕:(

最佳答案

如果您需要计算小于 teamCount 的 2 的最小次方(不是倍数),那么这可能是最好的方法。取对数是一项代价高昂的操作,可能比简单的循环花费更多的时间。

更新这是一个使用按位运算的算法 (C++)(http://aggregate.org/MAGIC/,下一个最大的 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);
}

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

关于C#数学题: smallest power of 2 bigger than X?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5525122/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com