如何找到数字的两个幂

时间:2014-02-04 05:35:27

标签: c

我有一个数字,功率为2,例如128 ==这是2次幂7。

如何找到数字的两个幂。

只需极少的代码。

3 个答案:

答案 0 :(得分:6)

试试这个,

int a = 128, ret = 0;
while (a) { ret++; a >>= 1; }

或者,

int a = 128, ret = 0;
#define check(i) if ((-1 << i) & a) { ret += i; a >>= i; }
check (16)
check (8)
check (4)
check (2)
check (1)

这是有效的,因为-1 == 0xffffffffff... a.k.a.是一个无尽的1字符串。所以我基本上执行二进制搜索来找到最高设置位的索引。

答案 1 :(得分:0)

这应该这样做:

int num=64,pow=0;
while(num){++pow;num>>=1;}

它非常简单,因为它使用字节操作,所以它也很快

答案 2 :(得分:0)

关于其他答案,我认为在进入while循环之前,必须将数字递减以获得正确答案:

  public static int getPowersOfTwo(int number) {
    int powersOfTwo = 0;
    number--;  // has the effect of zeroing out the most significant non-zero bit
    while (number > 0) {
      powersOfTwo++;
      number >>= 1;
    }

    return powersOfTwo;
  }
相关问题