加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 23:58:20 所属栏目:百科 来源:网络整理
导读:public int CalcBrackets(int teamCount) { int positions = 1; while (positions teamCount) positions *= 2; return positions; } 我想要的最小数字是2的幂,大于或等于teamCount.这真的是最好的方法吗?肯定看起来很可怕:( 解决方法 如果你需要计算的最小
public int CalcBrackets(int teamCount)
    {
        int positions = 1;

        while (positions < teamCount)
            positions *= 2;

        return positions;
    }

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

解决方法

如果你需要计算的最小功率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);
}

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读