reference:
http://www.geeksforgeeks.org/position-of-rightmost-set-bit/
Problem Definition:
Write a one line C function to return position of first 1 from right to left, in binary representation of an Integer.
Solution:
Example 18(010010)
1. Take two's complement(i.e. -n) of the given no as all bits are reverted
except the first '1' from right to left (10111)
2 Do an bit-wise & with original no, this will return no with the
required one only (00010)
3 Take the log2 of the no, you will get position -1 (1)
4 Add 1 (2)
Code:
unsigned int getFirstSetBitPos(int n)
{
return log2(n&-n)+1;//or log2(n & (n^(n-1)))+1
}
本文介绍了一种高效的方法来确定一个整数二进制表示中从右向左计数的第一个1的位置。该方法通过取整数的补码、与原始整数进行按位与操作、再对结果取对数并加1来实现。
556

被折叠的 条评论
为什么被折叠?



