最接近2的力量

Mic*_* M. 3 c

给定无符号整数a(小于或等于1024),我需要找到p满足以下条件的数字:

  • 最低 p >= a
  • p 是2的力量

我确信有一个更好的解决方案,使用按位运算符.
你有更好的解决方案吗?

unsigned int closest_pow2(unsigned int a)
{
  if (a == 0 || a > 1024) return 0; //error, never happen
  if (a == 1) return 1;
  if (a == 2) return 2;
  if (a <= 4) return 4;
  if (a <= 8) return 8;
  if (a <= 16) return 16;
  if (a <= 32) return 32;
  if (a <= 64) return 64;
  if (a <= 128) return 128;
  if (a <= 256) return 256;
  if (a <= 512) return 512;
  if (a <= 1024) return 1024;
}
Run Code Online (Sandbox Code Playgroud)

NPE*_*NPE 7

以下是没有相对昂贵的条件语句或循环:

unsigned next_power_of_two(unsigned int x) {
   x = x - 1; 
   x = x | (x >> 1); 
   x = x | (x >> 2); 
   x = x | (x >> 4); 
   x = x | (x >> 8); 
   return x + 1; 
} 
Run Code Online (Sandbox Code Playgroud)

  • 我花了比@delnan更长的时间来得出结论它是可行的(用一些无符号的整数进行剪切 - 粘贴 - 点击运行测试),但没有挥手.但考虑到选择性很好的描述性名称,并且它是6行代码,可读性永远不会成为一个休闲问题.俏皮.+1. (2认同)