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 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的幂. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |