找到的最高位组没有循环一个32位数字的指数明显 [英] find the index of the highest bit set of a 32-bit number without loops obviously

查看:126
本文介绍了找到的最高位组没有循环一个32位数字的指数明显的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是一个艰难的(至少我的日子不好过:P):

Here's a tough one(atleast i had a hard time :P):

找到的最高位组的一个32位数字的指数,而无需使用任何环路。

find the index of the highest bit set of a 32-bit number without using any loops.

推荐答案

递归:

int firstset(int bits) {        
     return (bits & 0x80000000) ? 31 : firstset((bits << 1) | 1) - 1;
}

  • 假设 [31,...,0] 索引
  • 返回-1,如果没有位设置
  • | 1 prevents被封盖的移动次数,直到堆栈溢出 1 为止(32)
  • 未尾递归:)
    • Assumes [31,..,0] indexing
    • Returns -1 if no bits set
    • | 1 prevents stack overflow by capping the number of shifts until a 1 is reached (32)
    • Not tail recursive :)
    • 这篇关于找到的最高位组没有循环一个32位数字的指数明显的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆