如何找到第一个置位的索引 [英] How to find index of first set bit
本文介绍了如何找到第一个置位的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否存在按位解决方案来找到仅设置一个位的掩码中第一个设置位的索引? 例如对于8,它将是3,对于16 => 4,依此类推.没有循环PLZ. 我能想到的最好的解决方案是创建一个从位到索引的映射.
Is there bitwise solution to find the index of first set bit in mask with only one bit set? e.g. for 8 it would be 3, for 16 => 4 and so on. No loops plz. The best solution I can come up with is to createa map of bit to index.
推荐答案
function firstBit(x) {
return Math.floor(
Math.log(x | 0) / Math.log(2)
) + 1;
}
i=4; console.log(i.toString(2), firstBit(i)); // 100 3
i=7; console.log(i.toString(2), firstBit(i)); // 111 3
i=8; console.log(i.toString(2), firstBit(i)); // 1000 4
这篇关于如何找到第一个置位的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文